新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c#中portabledeviceapi如何使用

发布时间:2023-08-21 07:57:13

c#中portabledeviceapi如何使用

在C#中使用PortableDeviceAPI可以通过以下步骤进行:
1. 添加对PortableDeviceApiLib库的援用。可以通过右键点击项目,选择“添加援用”,然后在COM选项卡中找到“PortableDeviceApiLib”并添加。
2. 在代码中创建PortableDeviceManager对象,并使用其方法连接到装备。例如:
```csharp
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]);
```
3. 使用PortableDevice对象进行操作,如获得装备信息、罗列文件、上传和下载文件等。例如:
```csharp
// 获得装备名称
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的基本用法,你可以根据自己的需求进行扩大和修改。