在C#中使用PortableDeviceAPI可以通過以下步驟進行:
添加對PortableDeviceApiLib庫的引用。可以通過右鍵點擊項目,選擇“添加引用”,然后在COM選項卡中找到“PortableDeviceApiLib”并添加。
在代碼中創建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]);
// 獲取設備名稱
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的基本用法,你可以根據自己的需求進行擴展和修改。