How to detect using c# if a pendrive is plugged into a USB port?

前端 未结 4 1429
孤街浪徒
孤街浪徒 2020-12-04 16:52

Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port? Programatically (in C# preferably) or through some tool. Basically I\'d imagine a clien

4条回答
  •  时光说笑
    2020-12-04 17:35

    [Assuming Windows, given the C# remark. Please tag accordingly]

    Yes, this is possible. And it is possible to get the details of the file. It will require programming, though. Watch for WM_DEVICECHANGE and re-enumerate drives afterwards. It will get you USB pendrives, but also SD cards. I expect that's a bonus for you.

    To get more details once you know a drive has arrived, use System.IO.FileSystemWatcher

    Update I found a better solution - if you register for volume interface notifications, you'll get the volume path for the new drive. First, create a DEV_BROADCAST_DEVICEINTERFACE with dbcc_classguid=GUID_DEVINTERFACE_VOLUME. Then pass this to RegisterDeviceNotification(). You will again get a WM_DEVICECHANGE but you can now cast the lParam from the message to DEV_BROADCAST_DEVICEINTERFACE*.

    You can pass the dbcc_name you receive to GetVolumeNameForVolumeMountPoint(). You can also pass all drive letters from GetLogicalDriveStrings() to GetVolumeNameForVolumeMountPoint(). You'll have one matching volume name; this is the new drive.

提交回复
热议问题