C#显示本机IP和MAC地址的代码!
下面这段程序为什么不能显示IP地址呢????
编译运行后会在textBox1里显示System.String[],
请问:这是哪里错了呀????????
ManagementClass mc;
mc = new ManagementClass( "Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection moc = mc.GetInstances();
//MessageBox.Show(moc.Count.ToString());
foreach (ManagementObject mo in moc)
{
if (mo[ "IPEnabled "].ToString() == "True ")
{
textBox1.Text += mo[ "IPAddress "].ToString();
textBox2.Text += mo[ "MACAddress "].ToString();
}
}
------解决方案--------------------获取本机IP
string strHostIP= " ";
IPHostEntry oIPHost=Dns.Resolve(Environment.MachineName);
if(oIPHost.AddressList.Length> 0)
strHostIP=oIPHost.AddressList[0].ToString();
获取MAC
using System.Management;
//get the MAC address
ManagementClass mc=new ManagementClass( "Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection moc=mc.GetInstances();
string[] MacAddress=new string[2];
int ii=0;
foreach(ManagementObject mo in moc)
{
if((bool)mo[ "IPEnabled "]==true)
{
MacAddress[ii]=mo[ "MacAddress "].ToString();
ii++;
}
mo.Dispose();
}
------解决方案--------------------你错在 if (mo[ "IPEnabled "].ToString() == "True ")
这行
if (mo[ "IPEnabled "].ToString() == "true ")
就对了,建议不要textBox1.Text +=
先定义个String ,最后在赋值
------解决方案--------------------将其改为
ManagementClass mc;
mc = new ManagementClass( "Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection moc = mc.GetInstances();
//MessageBox.Show(moc.Count.ToString());
foreach (ManagementObject mo in moc)
{
if (mo[ "IPEnabled "].ToString() == "True ")