c#中portabledeviceapi怎么使用

c#
1064
2023/8/19 10:11:21
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中使用PortableDeviceAPI可以通过以下步骤进行:

  1. 添加对PortableDeviceApiLib库的引用。可以通过右键点击项目,选择“添加引用”,然后在COM选项卡中找到“PortableDeviceApiLib”并添加。

  2. 在代码中创建PortableDeviceManager对象,并使用其方法连接到设备。例如:

PortableDeviceManager deviceManager = new PortableDeviceManager();
deviceManager.RefreshDeviceList();
// 获取设备列表
string[] deviceIds = new string[1];
uint count = 1;
deviceManager.GetDevices(deviceIds, ref count);
// 连接到设备
PortableDevice device = new PortableDevice();
device.Open(deviceIds[0]);
  1. 使用PortableDevice对象进行操作,如获取设备信息、列举文件、上传和下载文件等。例如:
// 获取设备名称
string deviceName;
device.GetDeviceFriendlyName(out deviceName);
// 列举设备中的文件
IPortableDeviceContent content;
device.Content(out content);
IPortableDeviceProperties properties;
content.Properties(out properties);
IPortableDevicePropVariantCollection objectIds = new PortableDeviceTypesLib.PortableDevicePropVariantCollection() as IPortableDevicePropVariantCollection;
content.EnumObjects(0, deviceIds[0], null, out objectIds);
uint numObjects;
objectIds.GetCount(out numObjects);
for (uint i = 0; i < numObjects; i++)
{
var propertyValue = new PortableDeviceApiLib._tagpropertykey();
objectIds.GetAt(i, out propertyValue);
IPortableDeviceProperties currentProperties;
content.Properties(out currentProperties);
PortableDeviceApiLib.IPortableDeviceValues values;
currentProperties.GetValues(propertyValue.ToString(), null, out values);
// 获取文件名
string fileName;
values.GetStringValue(ref PortableDevicePKeys.WPD_OBJECT_NAME, out fileName);
Console.WriteLine("文件名:" + fileName);
}
// 上传文件到设备
PortableDeviceApiLib.IPortableDeviceContent2 content2 = device as PortableDeviceApiLib.IPortableDeviceContent2;
PortableDeviceApiLib.IStream wpdStream;
content2.CreateObjectWithPropertiesAndData(
PortableDevicePKeys.WPD_OBJECT_FORMAT_UNSPECIFIED,
"test.jpg",
null,
out wpdStream,
0);
FileStream fileStream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
IntPtr pcbWritten = IntPtr.Zero;
wpdStream.Write(buffer, (uint)bytesRead, pcbWritten);
} while (bytesRead > 0);
wpdStream.Commit(0);
Marshal.ReleaseComObject(wpdStream);

以上是PortableDeviceAPI的基本用法,你可以根据自己的需求进行扩展和修改。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#程序集重新载入的方法是什么