using System.Management;(要添加引用)
//取CPU号
public string GetCpuID()
{
try
{
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
string strCpuID = null ;
foreach( ManagementObject mo in moc )
{
strCpuID = mo.Properties["ProcessorId"].Value.ToString();
break;
}
return strCpuID;
}
catch
{
return "";
}
}
//取第一块硬盘号
public string GetHardDiskID()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
string strHardDiskID = null ;
foreach(ManagementObject mo in searcher.Get())
{
strHardDiskID = mo["ModuleNumber"].ToString().Trim();
if(strHardDiskID != "")
{
break;
}
}
return strHardDiskID ;
}
catch
{
return "";
}
}//end
//取第一块网卡号
public string GetNetworkID()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
string strNetworkID = null ;
foreach(ManagementObject mo in searcher.Get())
{
strNetworkID = mo["MACAddress"].ToString().Trim();
if(strNetworkID != "")
{
break;
}
}
return strNetworkID ;
}
catch
{
return "";
}
}//end
//取串口
public int getport(int portnum)
{
//链接服务器
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
//检测是否已存在相同串口的站点,并获取PORT值
foreach(DirectoryEntry e in root.Children)
{
if(e.SchemaClassName == "IIsWebServer")
{
if(e.Properties["ServerBindings"].Value != null)
{
int strstart = e.Properties["ServerBindings"].Value.ToString().IndexOf(":",0);
int strend = e.Properties["ServerBindings"].Value.ToString().IndexOf(":",strstart+1);
string thisport = e.Properties["ServerBindings"].Value.ToString().Substring((strstart+1),(strend-strstart-1));
if(thisport == portnum.ToString())
{
portnum++;
portnum = getport(portnum);
break;
}
}
}
}
return portnum;
}
二,
using System.Net.NetworkInformation;
NetworkInterface[] ni = NetworkInterface.GetAllNetworkInterfaces();
for (int i = 0; i < ni.Length; i++)
{
if (ni[i].NetworkInterfaceType == NetworkInterfaceType.Ethernet && ni[i].OperationalStatus == OperationalStatus.Up)
{
return ni[i].GetPhysicalAddress().ToString();
}
}
三,
//返回Mac地址
public string GetMacAddress()
{
ManagementClass mc;
ManagementObjectCollection moc;
try
{
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
moc = mc.GetInstances();
}
catch
{
return "无法得到网卡物理地址!";
}
//****先得到网卡数目
int i = 0;
foreach(ManagementObject mo in moc)
{
if((bool)mo["IPEnabled"] == true)
{
i++;
}
mo.Dispose();
}
//***赋值给数组
ManagementClass mc_2 = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc_2 = mc_2.GetInstances();
string []array = new string[i];
int j = 0;
foreach(ManagementObject mo in moc_2)
{
if((bool)mo["IPEnabled"] == true)
{
string temp = mo["MacAddress"].ToString();
temp = temp.Replace(":","-");
array[j] = temp;
j++;
}
mo.Dispose();
}
string retv="";
foreach(string s in array)
retv+=s;
if(retv.Length>17)
{
retv=retv.Substring(0,17);
}
return retv;
}