这个小程序主要使用了System.Management 中的ManagementClass,ManagementObjectCollection, ManagementObject等来获取系统的信息,并进行相应的设置,在.NET中都是相当简单的,只用调用相应的函数就可以了,这里主要使用了网卡信息察看和设置。对其他硬件信息的管理也是差不多的,有需要的朋友可以察看
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/setgateways_method_in_class_win32_networkadapterconfiguration.asp
using System.Management;
static void SetNetworkAdapter()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
//设置ip地址和子网掩码
inPar = mo.GetMethodParameters( "EnableStatic" );
inPar["IPAddress"] = new string[]
{ "10.22.21.111","192.168.10.9" };
inPar["SubnetMask"] = new string[]
{ "255.255.255.0","255.255.255.0" };
outPar = mo.InvokeMethod( "EnableStatic", inPar, null );
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[]
{ "10.22.21.1","192.168.10.1"};
outPar = mo.InvokeMethod( "SetGateways", inPar, null );
//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[]
{"179.32.42.4","179.32.42.5"};
outPar = mo.InvokeMethod( "SetDNSServerSearchOrder" ,inPar,null);
break;
}
}
/**//// <summary>
/// 显示当前的ip,子网掩码,网关,DNS,网卡地址等信息
/// </summary>
static void ShowNetworkAdapterInfo()
{
Console.WriteLine( "****** Current Network Adapter Information ******" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
Console.WriteLine( "{0}/n SVC: '{1}' MAC: [{2}]", (string) mo["Caption"],
(string) mo["ServiceName"], (string) mo["MACAddress"] );
string[] addresses = (string[]) mo[ "IPAddress" ];
string[] subnets = (string[]) mo[ "IPSubnet" ];
string[] gateways = (string[]) mo["DefaultIPGateway"];
string[] dnses = (string[])mo["DNSServerSearchOrder"];
Console.WriteLine( " Addresses :" );
foreach(string sad in addresses)
Console.WriteLine( "/t'{0}'", sad );
Console.WriteLine( " Subnets :" );
foreach(string sub in subnets )
Console.WriteLine( "/t'{0}'", sub );
Console.WriteLine(" Gateways:");
foreach(string gw in gateways )
Console.WriteLine( "/t'{0}'", gw );
Console.WriteLine(" DNS:");
foreach(string dns in dnses )
Console.WriteLine( "/t'{0}'", dns );
}
}