获取.Net Core 2.1中USB存储设备的序列号 [英] Get the serial number of USB storage devices in .Net Core 2.1

查看:175
本文介绍了获取.Net Core 2.1中USB存储设备的序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 .Net Core 2.1 中获得USB存储设备的序列号

How can I get the serial number of USB storage devices in .Net Core 2.1?

I找到了不同的解决方案,但遗憾的是,由于.Net Core中缺少Windows注册表和WMI支持,它们无法正常工作。

I found different solutions, but sadly they don't work due the lack of Windows registry and WMI support in .Net Core.

在Powershell中,它非常简单,但是我无法在 PowerShell核心

In Powershell it's really simple, but I wasn't able to find an implementation in Powershell Core.

PS C:\> Get-Disk | Select-Object SerialNumber

SerialNumber
------------
0008_0D02_0021_9852.

我更喜欢在客户端(Win,Linux,Mac)上没有额外安装要求的解决方案。

I prefer a solution with no extra installation requirements on the clients (Win, Linux, Mac).

推荐答案

该类在WMI上执行一系列查询 Win32_DiskDrive 类及其关联器: Win32_DiskDriveToDiskPartition CIM_LogicalDiskBasedOnPartition ,以检索系统(本地或远程)上活动USB驱动器上的信息。

This Class performs a series of queries on the WMI Win32_DiskDrive class and its associators: Win32_DiskDriveToDiskPartition and CIM_LogicalDiskBasedOnPartition, to retrieve informations on the active USB Drives on a System (local or remote).

由于您只是询问了USB驱动器序列号,因此它似乎是多余的(可能是因为)。但是,您永远都不知道下一步需要什么,它可能对其他人有用。

It might seem redundant (probably because it is), since you just asked for the USB Drives Serial Number. But, you never know what you will need next, and it could be useful to someone else.

它需要用于.Net Core 2.1的Microsoft .Net System.Management 4.5 (NuGet程序包)

并使用Visual Studio NuGet程序包管理器安装。

关于 Linux 支持,请阅读:

Windows管理规范现在使用Linux 4.13的正式总线

It requires Microsoft .Net System.Management 4.5 for .Net Core 2.1 (NuGet Package)
Can be easily found and installed using the Visual Studio NuGet Package Manager.
About Linux support, read here:
Windows Management Instrumentation Now A Formal Bus With Linux 4.13

此外,请密切注意适用于.NET的Windows兼容包核心

新的跨平台程序集会不断添加和更新。

Also, keep an eye out for Windows Compatibility Pack for .NET Core.
New cross-platform assemblies are constantly added and updated.

主类实现了所有必需的功能,并且具有相当简单的结构。

WMI查询使用关联器语法,一种关联的方法WMI类对象彼此相关。

类属性的含义不言而喻。

The main class implements all the required functionalities and it has quite a simple structure.
The WMI queries use the Associator syntax, a method to correlate WMI class objects related to each other.
The Class properties meaning is self-explanatory.

可以通过以下方式实例化:

SystemUSBDrives systemUSBDrives = new SystemUSBDrives( [Computer Name]);

Can be instantiated this way:
SystemUSBDrives systemUSBDrives = new SystemUSBDrives("[Computer Name]");

[计算机名称] 为空或为空时,它将使用本地计算机名称。

When [Computer Name] is null or empty, it uses the Local Machine name.

要获取USB设备及其属性列表,请调用 GetUSBDrivesInfo()方法:

To get the List of USB Devices and their properties, call the GetUSBDrivesInfo() method:

var USBDrivesEnum = systemUSBDrives.GetUSBDrivesInfo([UserName],[Password],[Domain]);

var USBDrivesEnum = systemUSBDrives.GetUSBDrivesInfo([UserName], [Password], [Domain]);

[用户名],[密码],[域] 用于连接到NT域。

如果不需要,这些参数可以为null或为空g。

[UserName], [Password], [Domain] are used to connect to a NT Domain.
These parameters, if not needed, can be null or an empty string.

示例类实例化和函数调用本地计算机,无身份验证):

SystemUSBDrives systemUSBDrives = new SystemUSBDrives(null);
var USBDrivesEnum = systemUSBDrives.GetUSBDrivesInfo(null, null, null);






测试于:

Visual Studio Pro 15.7.6-15.8.5 .br

.Net Framework Core 2.1

C#6.0-> 7.3

.Net系统管理4.5


Tested on:
Visual Studio Pro 15.7.6 - 15.8.5
.Net Framework Core 2.1
C# 6.0 -> 7.3
.Net System.Management 4.5

using System.Management;

public class SystemUSBDrives
{
    string m_ComputerName = string.Empty;
    public SystemUSBDrives(string ComputerName)
    {
        this.m_ComputerName = string.IsNullOrEmpty(ComputerName)
                            ? Environment.MachineName
                            : ComputerName;
    }

    public class USBDriveInfo
    {
        public bool Bootable { get; private set; }
        public bool BootPartition { get; private set; }
        public string Caption { get; private set; }
        public string DeviceID { get; private set; }
        public UInt32 DiskIndex { get; private set; }
        public string FileSystem { get; private set; }
        public string FirmwareRevision { get; private set; }
        public UInt64 FreeSpace { get; private set; }
        public string InterfaceType { get; private set; }
        public string LogicalDisk { get; private set; }
        public bool MediaLoaded { get; private set; }
        public string MediaType { get; private set; }
        public string Model { get; private set; }
        public UInt32 Partitions { get; private set; }
        public UInt64 PartitionBlockSize { get; private set; }
        public UInt64 PartitionNumberOfBlocks { get; private set; }
        public UInt64 PartitionStartingOffset { get; private set; }
        public string PNPDeviceID { get; private set; }
        public bool PrimaryPartition { get; private set; }
        public string SerialNumber { get; private set; }
        public UInt64 Size { get; private set; }
        public string Status { get; private set; }
        public bool SupportsDiskQuotas { get; private set; }
        public UInt64 TotalCylinders { get; private set; }
        public UInt32 TotalHeads { get; private set; }
        public UInt64 TotalSectors { get; private set; }
        public UInt64 TotalTracks { get; private set; }
        public UInt32 TracksPerCylinder { get; private set; }
        public string VolumeName { get; private set; }
        public string VolumeSerialNumber { get; private set; }

        public void GetDiskDriveInfo(ManagementObject DiskDrive)
        {
            this.Caption = DiskDrive["Caption"]?.ToString();
            this.DeviceID = DiskDrive["DeviceID"]?.ToString();
            this.FirmwareRevision = DiskDrive["FirmwareRevision"]?.ToString();
            this.InterfaceType = DiskDrive["InterfaceType"]?.ToString();
            this.MediaLoaded = (bool?)DiskDrive["MediaLoaded"] ?? false;
            this.MediaType = DiskDrive["MediaType"]?.ToString();
            this.Model = DiskDrive["Model"]?.ToString();
            this.Partitions = (UInt32?)DiskDrive["Partitions"] ?? 0;
            this.PNPDeviceID = DiskDrive["PNPDeviceID"]?.ToString();
            this.SerialNumber = DiskDrive["SerialNumber"]?.ToString();
            this.Size = (UInt64?)DiskDrive["Size"] ?? 0L;
            this.Status = DiskDrive["Status"]?.ToString();
            this.TotalCylinders = (UInt64?)DiskDrive["TotalCylinders"] ?? 0;
            this.TotalHeads = (UInt32?)DiskDrive["TotalHeads"] ?? 0U;
            this.TotalSectors = (UInt64?)DiskDrive["TotalSectors"] ?? 0;
            this.TotalTracks = (UInt64?)DiskDrive["TotalTracks"] ?? 0;
            this.TracksPerCylinder = (UInt32?)DiskDrive["TracksPerCylinder"] ?? 0;
        }

        public void GetDiskPartitionInfo(ManagementObject Partitions)
        {
            this.Bootable = (bool?)Partitions["Bootable"] ?? false;
            this.BootPartition = (bool?)Partitions["BootPartition"] ?? false;
            this.DiskIndex = (UInt32?)Partitions["DiskIndex"] ?? 0;
            this.PartitionBlockSize = (UInt64?)Partitions["BlockSize"] ?? 0;
            this.PartitionNumberOfBlocks = (UInt64?)Partitions["NumberOfBlocks"] ?? 0;
            this.PrimaryPartition = (bool?)Partitions["PrimaryPartition"] ?? false;
            this.PartitionStartingOffset = (UInt64?)Partitions["StartingOffset"] ?? 0;
        }

        public void GetLogicalDiskInfo(ManagementObject LogicalDisk)
        {
            this.FileSystem = LogicalDisk["FileSystem"]?.ToString();
            this.FreeSpace = (UInt64?)LogicalDisk["FreeSpace"] ?? 0;
            this.LogicalDisk = LogicalDisk["DeviceID"]?.ToString();
            this.SupportsDiskQuotas = (bool?)LogicalDisk["SupportsDiskQuotas"] ?? false;
            this.VolumeName = LogicalDisk["VolumeName"]?.ToString();
            this.VolumeSerialNumber = LogicalDisk["VolumeSerialNumber"]?.ToString();
        }
    }

    public List<USBDriveInfo> GetUSBDrivesInfo(string UserName, string Password, string Domain)
    {
        List<USBDriveInfo> WMIQueryResult = new List<USBDriveInfo>();
        ConnectionOptions ConnOptions = GetConnectionOptions(UserName, Password, Domain);
        EnumerationOptions mOptions = GetEnumerationOptions(false);
        ManagementScope mScope = new ManagementScope(@"\\" + this.m_ComputerName + @"\root\CIMV2", ConnOptions);
        SelectQuery selQuery = new SelectQuery("SELECT * FROM Win32_DiskDrive " +
                                                "WHERE InterfaceType='USB'");
        mScope.Connect();

        using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mScope, selQuery, mOptions))
        {
            foreach (ManagementObject moDiskDrive in moSearcher.Get())
            {
                USBDriveInfo usbInfo = new USBDriveInfo();
                usbInfo.GetDiskDriveInfo(moDiskDrive);

                var relQuery = new RelatedObjectQuery("Associators of {Win32_DiskDrive.DeviceID='" +
                                                      moDiskDrive.Properties["DeviceID"].Value.ToString() + "'} " +
                                                      "where AssocClass=Win32_DiskDriveToDiskPartition");
                using (ManagementObjectSearcher moAssocPart = new ManagementObjectSearcher(mScope, relQuery, mOptions))
                {
                    foreach (ManagementObject moAssocPartition in moAssocPart.Get())
                    {
                        usbInfo.GetDiskPartitionInfo(moAssocPartition);
                        relQuery = new RelatedObjectQuery("Associators of {Win32_DiskPartition.DeviceID='" +
                                                          moAssocPartition.Properties["DeviceID"].Value.ToString() + "'} " +
                                                          "where AssocClass=CIM_LogicalDiskBasedOnPartition");

                        using (ManagementObjectSearcher moLogDisk = new ManagementObjectSearcher(mScope, relQuery, mOptions))
                        {
                            foreach (ManagementObject moLogDiskEnu in moLogDisk.Get())
                            {
                                usbInfo.GetLogicalDiskInfo(moLogDiskEnu);
                                moLogDiskEnu.Dispose();
                            }
                        }
                        moAssocPartition.Dispose();
                    }
                    WMIQueryResult.Add(usbInfo);
                }
                moDiskDrive.Dispose();
            }
            return WMIQueryResult;
        }
    }   //GetUSBDrivesInfo()

    private ConnectionOptions GetConnectionOptions(string UserName, string Password, string DomainAuthority)
    {
        ConnectionOptions ConnOptions = new ConnectionOptions()
        {
            EnablePrivileges = true,
            Timeout = ManagementOptions.InfiniteTimeout,
            Authentication = AuthenticationLevel.PacketPrivacy,
            Impersonation = ImpersonationLevel.Impersonate,
            Username = UserName,
            Password = Password,
            Authority = DomainAuthority  //Authority = "NTLMDOMAIN:[domain]"
        };
        return ConnOptions;
    }

    private System.Management.EnumerationOptions GetEnumerationOptions(bool DeepScan)
    {
        System.Management.EnumerationOptions mOptions = new System.Management.EnumerationOptions()
        {
            Rewindable = false,        //Forward only query => no caching
            ReturnImmediately = true,  //Pseudo-async result
            DirectRead = true,         //True => Direct access to the WMI provider, no super class or derived classes
            EnumerateDeep = DeepScan   //False => only immediate derived class members are returned.
        };
        return mOptions;
    }
}  //SystemUSBDrives

这篇关于获取.Net Core 2.1中USB存储设备的序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆