C# 获得本地通用网卡信息的示例代码

    可以通过使用命名空间下的ManagementObjectSearcher类及其方法Get来获得通用网卡信息。

    其中,最重要的是ManagementObjectSearcher构造函数的输入参数,可以传入以下的QueryString。

    SELECT * FROM Win32_NetworkAdapterConfiguration

    以下的例子为将本地网卡的配置信息写入一个文件并保存,代码如下:

    
    using System.IO;
    using System.Linq;
    using System.Management;
    
    namespace ConsoleApp
    {
      class Program
      {
        static void Main(string[] args)
        {
          ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration") ;
          ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
          StreamWriter writer = new StreamWriter("result.csv");
          bool isFirstRow = true;
          foreach (ManagementObject managementObject in managementObjectCollection)
          {
            string header = string.Empty;
            string content = string.Empty;
            string separator1 = ",";
            string separator2 = " | ";
            foreach (var item in managementObject.Properties)
            {
              if (isFirstRow)
              {
                header = $"{header}{separator1}{item.Name}";
              }
              string valueTemp = string.Empty;
              if (item.Value != null)
              {
                if (item.Value is string[] || item.Value is ushort[])
                {
                  string[] valuesStrTemp;
                  if(item.Value is ushort[])
                    valuesStrTemp = ((ushort[])item.Value).Select(x => x.ToString()).ToArray();
                  else
                    valuesStrTemp = item.Value as string[];
    
                  for (int i = 0; i < valuesStrTemp.Length; i++)
                  {
                    valueTemp = $"{valueTemp}{separator2}{valuesStrTemp[i]}";
                  }
                  if(valuesStrTemp.Length != 0)
                    valueTemp = valueTemp.Remove(0, separator2.Length);
                }
                else
                  valueTemp = item.Value.ToString();
              }
              content = $"{content}{separator1}{valueTemp}";
            }
            if (isFirstRow)
            {
              header = header.Remove(0, separator1.Length);
              writer.WriteLine(header);
              isFirstRow = false;
            }
            content = content.Remove(0, separator1.Length);
            writer.WriteLine(content);
          }
          writer.Close();
        }
      }
    }

    运行结果如下:

    以上就是C# 获得本地通用网卡信息的示例代码的详细内容,更多关于c# 获得网卡信息的资料请关注lingkb其它相关文章!