C # get portable devices connected to PC

I try to get all usb devices (including portable devices) in Windows 7 now I searched everything and did not find a good answer.

I tried this code:

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!");
    }
}

but I get this error:

interop type 'portabledeviceapilib.portabledevicemanagerclass' Cannot be deployed

Now I'm pretty stuck.

If you could help me with this code / give me an idea of ​​what I should do, it’s bad to be happy

all I need to do is get what type of USB is connected, if the phone is connected, or a mouse. I want to know what is connected.

Thanx ahead

+4
source share
2 answers

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();
    }
}
+3

@CodeFox , ListDevices() :

  • NuGet PortableDevices

  • 4 COM:

    • PortableDeviceClassExtension
    • PortableDeviceConnectApi
    • PortableDeviceTypes
    • PortableDeviceApi
  • dll obj\Debug 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();
+1

Source: https://habr.com/ru/post/1607116/


All Articles