Skip to content

Instantly share code, notes, and snippets.

@YcSmile
Last active September 28, 2019 13:56
Show Gist options
  • Save YcSmile/1bb0720660b63e82b530d61c1438c0ff to your computer and use it in GitHub Desktop.
Save YcSmile/1bb0720660b63e82b530d61c1438c0ff to your computer and use it in GitHub Desktop.
.NET 获取设备名称

https://bbs.csdn.net/topics/390453634

    /// <summary>
    /// 枚举win32 api
    /// </summary>
    public enum HardwareEnum
    {
        // 硬件
        Win32_Processor, // CPU 处理器
        Win32_PhysicalMemory, // 物理内存条
        Win32_Keyboard, // 键盘
        Win32_PointingDevice, // 点输入设备,包括鼠标。
        Win32_FloppyDrive, // 软盘驱动器
        Win32_DiskDrive, // 硬盘驱动器
        Win32_CDROMDrive, // 光盘驱动器
        Win32_BaseBoard, // 主板
        Win32_BIOS, // BIOS 芯片
        Win32_ParallelPort, // 并口
        Win32_SerialPort, // 串口
        Win32_SerialPortConfiguration, // 串口配置
        Win32_SoundDevice, // 多媒体设置,一般指声卡。
        Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP)
        Win32_USBController, // USB 控制器
        Win32_NetworkAdapter, // 网络适配器
        Win32_NetworkAdapterConfiguration, // 网络适配器设置
        Win32_Printer, // 打印机
        Win32_PrinterConfiguration, // 打印机设置
        Win32_PrintJob, // 打印机任务
        Win32_TCPIPPrinterPort, // 打印机端口
        Win32_POTSModem, // MODEM
        Win32_POTSModemToSerialPort, // MODEM 端口
        Win32_DesktopMonitor, // 显示器
        Win32_DisplayConfiguration, // 显卡
        Win32_DisplayControllerConfiguration, // 显卡设置
        Win32_VideoController, // 显卡细节。
        Win32_VideoSettings, // 显卡支持的显示模式。

        // 操作系统
        Win32_TimeZone, // 时区
        Win32_SystemDriver, // 驱动程序
        Win32_DiskPartition, // 磁盘分区
        Win32_LogicalDisk, // 逻辑磁盘
        Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。
        Win32_LogicalMemoryConfiguration, // 逻辑内存配置
        Win32_PageFile, // 系统页文件信息
        Win32_PageFileSetting, // 页文件设置
        Win32_BootConfiguration, // 系统启动配置
        Win32_ComputerSystem, // 计算机信息简要
        Win32_OperatingSystem, // 操作系统信息
        Win32_StartupCommand, // 系统自动启动程序
        Win32_Service, // 系统安装的服务
        Win32_Group, // 系统管理组
        Win32_GroupUser, // 系统组帐号
        Win32_UserAccount, // 用户帐号
        Win32_Process, // 系统进程
        Win32_Thread, // 系统线程
        Win32_Share, // 共享
        Win32_NetworkClient, // 已安装的网络客户端
        Win32_NetworkProtocol, // 已安装的网络协议
        Win32_PnPEntity,//all device
    }

///

/// WMI取硬件信息 /// /// /// /// public static string[] MulGetHardwareInfo(HardwareEnum hardType, string propKey) {

        List<string> strs = new List<string>();
        try
        {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    if (hardInfo.Properties[propKey].Value.ToString().Contains("COM"))
                    {
                        strs.Add(hardInfo.Properties[propKey].Value.ToString());
                    }

                }
                searcher.Dispose();
            }
            return strs.ToArray();
        }
        catch
        {
            return null;
        }
        finally
        { strs = null; }
    }
 //通过WMI获取COM端口
 string[] ss = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
// Class to contain the port info.
public class PortInfo
{
public string Name;
public string Description;
}
// Method to prepare the WMI query connection options.
public static ConnectionOptions PrepareOptions()
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;
options.EnablePrivileges = true;
return options;
}
// Method to prepare WMI query management scope.
public static ManagementScope PrepareScope(string machineName, ConnectionOptions options, string path)
{
ManagementScope scope = new ManagementScope();
scope.Path = new ManagementPath(@"\\" + machineName + path);
scope.Options = options;
scope.Connect();
return scope;
}
// Method to retrieve the list of all COM ports.
public static List<PortInfo> FindComPorts()
{
List<PortInfo> portList = new List<PortInfo>();
ConnectionOptions options = PrepareOptions();
ManagementScope scope = PrepareScope(Environment.MachineName, options, @"\root\CIMV2");
// Prepare the query and searcher objects.
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher portSearcher = new ManagementObjectSearcher(scope, objectQuery);
using (portSearcher)
{
string caption = null;
// Invoke the searcher and search through each management object for a COM port.
foreach (ManagementObject currentObject in portSearcher.Get())
{
if (currentObject != null)
{
object currentObjectCaption = currentObject["Caption"];
if (currentObjectCaption != null)
{
caption = currentObjectCaption.ToString();
if (caption.Contains("(COM"))
{
PortInfo portInfo = new PortInfo();
portInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
portInfo.Description = caption;
portList.Add(portInfo);
Console.WriteLine(caption);
}
}
}
}
}
return portList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment