wangyu1204

导航

学习C#下注册表编程:获取网卡信息(未控制异常)

随手写的一段,win7和xp sp2下测试可用,如果ip设置自动获取会报错。

using System;
using Microsoft.Win32;

namespace GetNetworkCardInfo
{
    class Program
    {
        static void Main(string[] args)
        {

            using (RegistryKey
                Root_Key = Registry.LocalMachine,
                NetworkCards_Key = Root_Key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards"))
            {
                foreach (string Key in NetworkCards_Key.GetSubKeyNames())
                {
                    string Description = (string)Root_Key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\" + Key).GetValue("Description");
                    string ServiceName = (string)Root_Key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\" + Key).GetValue("ServiceName");
                    Console.WriteLine("网卡:{0}",Description);
                    RegistryKey Interfaces_Key = Root_Key.OpenSubKey(@"SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\" + ServiceName);
                    Console.WriteLine("IP: {0}\n子网掩码:{1}\n网关:{2}\n", ((string[])Interfaces_Key.GetValue("IPAddress"))[0], ((string[])Interfaces_Key.GetValue("SubnetMask"))[0], ((string[])Interfaces_Key.GetValue("DefaultGateway"))[0]);
                    Console.ReadKey();
                }
            }
        }
    }
}

posted on 2011-12-14 20:02  wangyu1204a  阅读(390)  评论(0)    收藏  举报