“你调用的对象是空的。”

时间:2013-06-21 10:44:38

标签: c#-4.0

我正在尝试检索IP地址。 但它正在给出这个例外

  

对象引用未设置为对象的实例。

ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery query1 = new ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
ManagementObjectCollection queryCollection = searcher1.Get();

foreach (ManagementObject m in queryCollection)
{

    listBox2.Items.Add(m["DefaultIPGateway"].ToString());
}

2 个答案:

答案 0 :(得分:0)

尝试调试,但它看起来像下面之一:

  1. searcher1为空。
  2. 在foreach中,m [“DefaultIPGateway”]返回null
  3. listbox2为空。

答案 1 :(得分:0)

尝试:

ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery query1 = new ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
ManagementObjectCollection queryCollection = searcher1.Get();

foreach (ManagementObject m in queryCollection)
{
   if(m["DefaultIPGateway"] != null)
   {
     listBox2.Items.Add(m["DefaultIPGateway"].ToString());
   }
}