首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中获取USB-Stick的序列号

在C#中获取USB-Stick的序列号,可以通过使用Windows API和WMI(Windows Management Instrumentation)来实现。以下是一个简单的示例代码,用于获取连接到计算机的所有USB存储设备的序列号:

代码语言:csharp
复制
using System;
using System.Management;

public class USBDriveInfo
{
    public static void Main()
    {
        try
        {
            ManagementObjectCollection drives = GetUSBDrives();

            foreach (ManagementObject drive in drives)
            {
                Console.WriteLine("Device ID: {0}", drive["DeviceID"]);
                Console.WriteLine("PNP Device ID: {0}", drive["PNPDeviceID"]);
                Console.WriteLine("Serial Number: {0}", drive["VolumeSerialNumber"]);
                Console.WriteLine();
            }
        }
        catch (ManagementException e)
        {
            Console.WriteLine("An error occurred while querying for USB drives: {0}", e.Message);
        }

        Console.ReadLine();
    }

    private static ManagementObjectCollection GetUSBDrives()
    {
        // Create a new WMI query
        string query = "SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'";
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

        // Execute the query and return the results
        return searcher.Get();
    }
}

这段代码首先使用WMI查询所有接口类型为USB的磁盘驱动器。然后,它遍历查询结果,并输出每个USB存储设备的设备ID、PNP设备ID和序列号。

需要注意的是,这个方法只能获取已连接的USB存储设备的序列号。如果设备没有序列号,则此方法将不起作用。此外,如果有多个USB存储设备连接到计算机,则此方法将返回所有设备的序列号。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券