专业编程基础技术教程

网站首页 > 基础教程 正文

C#如何获取计算机或硬件信息 c#获取其他程序界面内容

ccvgpt 2024-12-26 12:11:18 基础教程 1 ℃

引言

在项目开发过程中,偶尔需要获取计算机环境信息,如操作系统、部分硬件等。根据获取的信息配置不同逻辑、提供硬件选择(如打印机、摄像头等)。本文将介绍几个常用的获取计算机或硬件信息方式。

系统

1、获取操作系统信息

/// <summary>
/// 操作系统信息
/// </summary>
/// <returns></returns>
public void GetOperatingSystem(ref string operatingSystem,ref string osArchitecture)
{
    try
    {
        using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("select * from Win32_OperatingSystem"))
        {
            foreach (ManagementObject ManagementObject in managementObjectSearcher.Get())
            {
                operatingSystem = Convert.ToString(ManagementObject["Caption"]);
                osArchitecture = Convert.ToString(ManagementObject["OSArchitecture"]);
                break;
            }
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
}

硬件

1、获取打印机

#region 方式一 使用 ManagementObject 类获取
/// <summary>
/// 获取打印机
/// </summary>
public List<string> GetPrinters()
{
    List<string> printerDevices = new List<string>();
    try
    {
        using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer"))
        {
            foreach (var device in searcher.Get())
            {
                if (device["Name"] != null)
                {
                    printerDevices.Add(Convert.ToString(device["Name"]));
                }
            }
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return printerDevices;
}
#endregion、

#region 方式二 使用 Printing 获取
/// <summary>
/// 获取打印机
/// </summary>
public List<string> GetInstalledPrinters()
{
    List<string> printerDevices = new List<string>();
    try
    {
        foreach (string printerName in PrinterSettings.InstalledPrinters)
        {
            if (!printerDevices.Contains(printerName))
            {
                printerDevices.Add(printerName);
            }
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return printerDevices;
}
#endregion

2、获取摄像头

/// <summary>
/// 获取摄像头设备
/// </summary>
public List<string> GetCameras()
{
    List<string> cameraDevices = new List<string>();
    try
    {
        using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
        {
            foreach (var device in searcher.Get())
            {
                if (device["Caption"] != null)
                {
                    cameraDevices.Add(Convert.ToString(device["Caption"]));
                }
            }
        }
    }
    catch(Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return cameraDevices;
}

3、获取硬盘

/// <summary>
/// 硬盘信息
/// </summary>
public List<DiskDrive> GetDiskDrive()
{
    List<DiskDrive> diskDevices = new List<DiskDrive>();
    try
    {
        using (ManagementClass managementClass = new ManagementClass("Win32_DiskDrive"))
        {
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                DiskDrive diskDrive = new DiskDrive();
                diskDrive.SerialNumber = Convert.ToString(managementObject.Properties["SerialNumber"].Value);
                diskDrive.SerialNumber = Convert.ToString(managementObject.Properties["Model"].Value);
                diskDrive.SerialNumber = Convert.ToString(managementObject.Properties["Size"].Value);
                diskDevices.Add(diskDrive);
            }
        }   
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return diskDevices;
}

4、获取计算机主板

/// <summary>
/// 主板信息
/// </summary>
public List<BaseBoard> GetMainBoardInfo()
{
    List<BaseBoard> baseBoardDevices = new List<BaseBoard>();
    try
    {
        using (ManagementClass managementClass = new ManagementClass("Win32_BaseBoard"))
        {
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                BaseBoard diskDrive = new BaseBoard();
                diskDrive.SerialNumber = Convert.ToString(managementObject.Properties["SerialNumber"].Value);
                diskDrive.Product = Convert.ToString(managementObject.Properties["Product"].Value);
                diskDrive.Version = Convert.ToString(managementObject.Properties["Version"].Value);
                diskDrive.Manufacturer = Convert.ToString(managementObject.Properties["Manufacturer"].Value);
                baseBoardDevices.Add(diskDrive);
            }
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return baseBoardDevices;
}

5、获取网络地址

/// <summary>
/// 获取网络地址
/// </summary>
/// <returns></returns>
public List<string> GetIPAddress()
{
    List<string> iPAddressList = new List<string>();
    try
    {
        IPAddress[] allIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
        foreach (IPAddress iPAddress in allIPAddresses)
        {
            if (iPAddress.AddressFamily.Equals(AddressFamily.InterNetwork))
            {
                // IP4
                iPAddressList.Add(iPAddress.ToString());
                continue;
            }
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return iPAddressList;
}

6、获取物理地址

#region 方式一 使用 NetworkInterface 类获取
public List<string> GetPhysicalAddress()
{
    List<string> physicalAddressList = new List<string>();
    try
    {
        NetworkInterface[] allNetworkInterface = NetworkInterface.GetAllNetworkInterfaces();
        string result = string.Empty;
        foreach (NetworkInterface networkInterface in allNetworkInterface)
        {
            result = networkInterface.GetPhysicalAddress().ToString();
            result = result.Insert(2, ":");
            result = result.Insert(5, ":");
            result = result.Insert(8, ":");
            result = result.Insert(11, ":");
            result = result.Insert(14, ":");
            physicalAddressList.Add(result);
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return physicalAddressList;
}
#endregion
#region 方式二 使用 ManagementObject 类获取
public static List<string> GetMacAddress()
{
    List<string> physicalAddressList = new List<string>();
    try
    {
        using (ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                if (managementObject["IPEnabled"] != null && managementObject["MacAddress"] != null)
                {
                    if ("true".Equals(Convert.ToString(managementObject["IPEnabled"]),StringComparison.OrdinalIgnoreCase))
                    {
                        physicalAddressList.Add(Convert.ToString(managementObject["MacAddress"]));
                    }
                }
            }
        }   
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return physicalAddressList;
}

7、获取处理器信息

/// <summary>
/// 处理器信息
/// </summary>
/// <returns></returns>
public string GetCPUInfo()
{
    StringBuilder stringBuilder = new StringBuilder();
    try
    {
        using (ManagementObjectCollection.ManagementObjectEnumerator searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor").Get().GetEnumerator())
        {
            if (searcher.MoveNext())
            {
                ManagementObject managementObject = (ManagementObject)searcher.Current;
                stringBuilder.Append(managementObject.GetPropertyValue("Name").ToString());
                stringBuilder.Append(",");
                stringBuilder.Append(managementObject.GetPropertyValue("CurrentClockSpeed").ToString());
                stringBuilder.Append(" Mhz,");
                stringBuilder.Append(Environment.ProcessorCount.ToString());
                stringBuilder.Append("核心");
            }
        }
    }
    catch (Exception exception)
    {
        throw new Exception(exception.Message);
    }
    return stringBuilder.ToString();
}

小结

以上是一些较常获取计算机硬件信息或系统信息。还有很多信息可以使用C#获取,这里不一一列举。如有不到之处,请多多包涵。大家可以留言,提供一些你知道的方法。

C#如何获取计算机或硬件信息 c#获取其他程序界面内容

Tags:

最近发表
标签列表