I'm collecting all networkadapterconfigurations from the Win32_NetworkAdapterConfiguration
class in C#.
I use this query:
private String strDetailedInterfaces =
@"SELECT *
FROM Win32_NetworkAdapterConfiguration
WHERE DHCPEnabled = 'TRUE'";
However, when selecting the networkadapter that I use to connect to the internet, it says that IPEnabled = false
and when I call the array with IPAddresses
, I get nullpointerexception (meaning that the array = null).
I call the addresses like this:
ManagementObject choosen = (ManagementObject)eInterfacesConfig.Current;
String[] ipAddresses = (String[]) choosen["IPAddress"];
lblIP.Text = ipAddresses[0];
eInterfacesConfig
is a ManagementObjectCollection.Enumerator
and
choosen is the current ManagementObject
out of the enumerator.
I try to change the text of a label (lblIP) to the first Ip address in the array. But this is where the exception throws.
Can someone explain why and perhaps point me into the right direction?
The following query returns two Win32_NetworkAdapterConfiguration
objects
on my Windows 8 machine:
ManagementObjectSearcher query =
new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE DHCPEnabled ='TRUE'");
ManagementObjectCollection queryCollection = query.Get();
queryCollection = query.Get();
foreach (ManagementObject currentConfig in queryCollection)
{
string[] addresses = (string[])currentConfig["IPAddress"];
Console.Out.WriteLine(currentConfig["Description"]);
if (addresses != null)
{
foreach (var addr in addresses)
{
Console.Out.WriteLine(addr);
}
}
}
The first adapter configuration is for the Microsoft Kernel Debug Network Adapter.
This adapter is used for remote kernel debugging. The DHCPEnabled
property
for this adapter is TRUE
. However there are no IP addresses
assigned to this adapter. This is the reason why the IPAddress
array is null.
The second adapter configuration is for my Intel Gigabit Network Adapter. There are two IP addresses assigned to the adapter.
Another reason why the IPAddress
array could be null is
for example a disconnected wireless network adapter.
So, in order to solve your NullReferenceException
you have to check the
IPAddress
array for null (please see the code above). Use the Description
property to identify the adapter configuration.