繁体   English   中英

C#获取连接到PC的便携式设备

[英]C# get portable devices connected to PC

我试图在Windows 7上获取所有USB设备(包括便携式设备),现在我搜遍了所有并没有找到一个好的答案。

我试过这段代码:

static void Main(string[] args)
{
    //
    // Get an instance of the device manager
    //
    PortableDeviceApiLib.PortableDeviceManagerClass devMgr
        = new PortableDeviceApiLib.PortableDeviceManagerClass();

    //
    // Probe for number of devices
    //
    uint cDevices = 1;
    devMgr.GetDevices(null, ref cDevices);

    //
    // Re-allocate if needed
    //
    if (cDevices > 0)
    {
        string[] deviceIDs = new string[cDevices];
        devMgr.GetDevices(deviceIDs, ref cDevices);

        for (int ndxDevices = 0; ndxDevices < cDevices; ndxDevices++)
        {
            Console.WriteLine("Device[{0}]: {1}",
                    ndxDevices + 1, deviceIDs[ndxDevices]);
        }
    }
    else
    {
        Console.WriteLine("No WPD devices are present!");
    }
}

但我得到这个错误:

interop type'portabledeviceapilib.portabledevicemanagerclass'无法嵌入

现在我很困惑。

如果你可以帮助我这个代码/给我一个想法我应该尝试什么,生病快乐

我只需要连接哪种类型的USB,连接手机或鼠标。 我想知道连接的是什么。

Thanx Ahead

我正在使用NuGet包PortableDevices (它基于Christophe Geers教程 )。

源自本教程的第一部分:

public void ListDevices()
{
    var devices = new PortableDeviceCollection();
    devices.Refresh();

    foreach (var device in devices)
    {
        device.Connect();
        Console.WriteLine(@"DeviceId: {0}, FriendlyName: {1}", device.DeviceId, device.FriendlyName);
        device.Disconnect();
    }
}

要扩展@ CodeFox的答案 ,并为了让他的代码ListDevices()工作:

  1. 下载NuGet包PortableDevices

  2. 添加对这4个COM库的引用:

    • PortableDeviceClassExtension
    • PortableDeviceConnectApi
    • PortableDeviceTypes
    • PortableDeviceApi
  3. obj\\Debug下获取dll并将它们放入bin\\Debug

    • Interop.PortableDeviceClassExtension.dll
    • Interop.PortableDeviceConnectApiLib.dll
    • Interop.PortableDeviceTypesLib.dll
    • Interop.PortableDeviceApiLib.dll

现在你可以使用这个函数,虽然FriendlyName似乎不起作用(它返回一个空字符串):

    private IDictionary<string, string> GetDeviceIds()
    {
        var deviceIds = new Dictionary<string, string>();
        var devices = new PortableDeviceCollection();
        devices.Refresh();
        foreach (var device in devices)
        {
            device.Connect();
            deviceIds.Add(device.FriendlyName, device.DeviceId);
            Console.WriteLine(@"DeviceId: {0}, FriendlyName: {1}", device.DeviceId, device.FriendlyName);
            device.Disconnect();
        }
        return deviceIds;
    }

我的下一步是从设备获取内容,这样做是这样的:

var contents = device.GetContents();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM