开发者

Strange results from win32_NetworkAdapterConfiguration

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Management.Instrumentation;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {


        public Form1()
        {

            {
                InitializeComponent();
            }

            // win32 class
            //http://msdn.microsoft.com/en-us/library/aa394216(v=vs.85).aspx

            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            ManagementObjectCollection queryCollection = query.Get();

            //foreach (ManagementObject mo in queryCollection)
            //{


            //    string[] addresses = (string[])mo["IPAddress"];
            //    string[] gateways = (string[])mo["DefaultIPGateway"];
            //    string[] Subnets = (string[])mo["IPSubnet"];


            //    foreach (string ipaddress in addresses)
            //    {

            //        listBox1.Items.Add(ipaddress);

            //    }
            //    foreach (string gateway in gateways)
            //    {

            //        TxtGateway.Text = (gateway);
            //    }
            //    foreach (string subnet in Subnets)
            //    {

            //        TxtSubnet.Text = (subnet);
            //    }

            //}


            try
            {
                query = new ManagementObjectSearcher(@"SELECT * FROM Win32_NetworkAdapter WHERE  Manufacturer != 'Microsoft' AND NOT PNPDeviceID LIKE 'ROOT\\%'");

                queryCollection = query.Get();

                foreach (ManagementObject mo in queryCollection)
                {



                    if (mo["MacAddress"] != null)
                    {

                        comboBox1.Items.Add(mo["Description"].ToString());


                    }

                    richTextBox1.AppendText("\n");
                }
            }


            catch (Exception ex)
            {

            }
        }

        string[] availabilityArray = new string[] {"", "Other", "Unknown", "Running or Full Power", "Warning", "In Test", "Not Applicable", "Power Off", "Off Line", "Off Duty", "Degraded", "Not Installed", "Install Error", "Power Save - Unknown" + "\n" +"The device is known to be in a power save state, but its exact status is unknown.", "Power Save - Low Power Mode" + "/n" +"The device is in a power save state, but still functioning, and may exhibit degraded performance.", "Power Save - Standby" + "/n" +"The device is not functioning, but could be brought to full power quickly.", "Power Cycle", "Power Save - Warning" + "/n" + "The device is in a warning state, though also in a power save state.",};
        string[] errorArray = new string[] { "Device is working properly.", "Device is not configured correctly.", "Windows cannot load the driver for this device.", "Driver for this device might be corrupted, or the system may be low on memory or other resources.", "Device is not working properly. One of its drivers or the registry might be corrupted.", "Driver for the device requires a resource that Windows cannot manage.", "Boot configuration for the device conflicts with other devices.", "Cannot filter.", "Driver loader for the device is missing.", "Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device.", "Device cannot start.", "Device failed.", "Device cannot find enough free resources to use.", "Windows cannot verify the device's resources.", "Device cannot work properly until the computer is restarted.", "Device is not working properly due to a possible re-enumeration problem.", "Windows cannot identify all of the resources that the device uses.", "Device is requesting an unknown resource type.", "Device drivers must be reinstalled.", "Failure using the VxD loader.", "Registry might be corrupted.", "System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.", "Device is disabled.", "System failure. If changing the device driver is ineffective, see the hardware documentation.", "Device is not present, not working properly, or does not have all of its drivers installed.", "Windows is still setting up the device.", "Windows is still setting up the device.", "Device does not have valid log configuration.", "Device drivers are not installed", "Device is disabled. The device firmware did not provide the required resources.", "Device is using an IRQ reso开发者_开发百科urce that another device is using.", "Device is not working properly. Windows cannot load the required device drivers.", };

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ManagementObjectSearcher intquery;

               intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
               ManagementObjectCollection queryCollection = intquery.Get();
                queryCollection = intquery.Get();

                //////////////////////////////////

                foreach (ManagementObject mo in queryCollection)
                {
                    string Dev = (mo["DeviceID"].ToString());

                    richTextBox1.Text = (Dev).ToString();
                    txtMacAdd.Text = (" " + mo["MacAddress"].ToString());
                    TxtAdapter.Text = (" " + mo["AdapterType"].ToString());
                    txtAvailability.Text = (" " + mo["Availability"].ToString());
                    txtCaption.Text = (" " + mo["Caption"].ToString());


                    txtDeviceID.Text = ("DeviceID = " + mo["DeviceID"].ToString());
                    txtErrorCode.Text = (mo["ConfigManagerErrorCode"].ToString());

                    ManagementObjectSearcher intquery1;
                    intquery1 = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID='"+Dev+"'}WHERE ResultClass=Win32_NetworkAdapterConfiguration");
                   //intquery1 = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration  WHERE IPEnabled = 'TRUE' ");
                    ManagementObjectCollection queryCollection1 = intquery1.Get();
                    queryCollection1 = intquery1.Get();

                    foreach (ManagementObject mo1 in queryCollection1)
                    {
                        string[] addresses = (string[])mo1["IPAddress"];
                        string[] gateways = (string[])mo1["DefaultIPGateway"];
                        string[] Subnets = (string[])mo1["IPSubnet"];

                        foreach (string ipaddress in addresses)
                        {

                            listBox1.Items.Add(ipaddress);

                        }
                        foreach (string gateway in gateways)
                        {

                            TxtGateway.Text = (gateway);
                        }
                        foreach (string subnet in Subnets)
                        {

                            richTextBox1.Text = (subnet);
                        }
                    }
                }
                }




            catch (Exception ex2)
            { 


            }
    }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {


            try
            {
                ManagementObjectSearcher intquery;
                intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
                ManagementObjectCollection queryCollection = intquery.Get();
                queryCollection = intquery.Get();

                foreach (ManagementObject mo in queryCollection)
                {
                    richTextBox1.Text = ("");
                    string thisstring = (mo["ConfigManagerErrorCode"].ToString());
                    int error;
                    int.TryParse(thisstring, out error);
                    MessageBox.Show(errorArray[error]);


                }
            }
            catch (Exception ex1) 
            {
                MessageBox.Show("PLease Select a Device");
            }

        }

        private void BtnAvailability_Click(object sender, EventArgs e)
        {
            try
            {
                ManagementObjectSearcher intquery;
                intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
                ManagementObjectCollection queryCollection = intquery.Get();
                queryCollection = intquery.Get();

                foreach (ManagementObject mo in queryCollection)
                {
                    richTextBox1.Text = ("");
                    string thisstring = (mo["Availability"].ToString());
                    int Avail;
                    int.TryParse(thisstring, out Avail);
                    MessageBox.Show(availabilityArray[Avail]);


                }
            }
            catch (Exception ex2)
            {
                MessageBox.Show("PLease Select a Device");
            }
        }
        }
}

For some reason the preceding code is giving me a subnet mask reading of 64. This only happens on my home network (which is wireles) and is fine at University.

If it gives any clues my IP Address ends in 64 so maybe there is somekind of mix up?!?!


Ok. Corrected code:

ManagementObjectSearcher intquery1 = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration  WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
ManagementObjectCollection queryCollection1 = intquery1.Get();
queryCollection1 = intquery1.Get();

foreach (ManagementObject mo1 in queryCollection1)
{
   string[] addresses = (string[])mo1["IPAddress"];
   string[] gateways = (string[])mo1["DefaultIPGateway"];
   string[] subnets = (string[])mo1["IPSubnet"];

   if (addresses != null)
   {
       listBox1.Items.Clear();
       foreach (string ip in addresses)
       {
           listBox1.Items.Add(ip);
       }
   }
   if (gateways != null)
   {
       foreach (string gateway in gateways)
       {
          TxtGateway.Text = (gateway);
       }
   }
   if (subnets != null)
   {
       foreach (string subnet in subnets)
       {
           richTextBox1.Text = (subnet);
       }
   }
}

You need to check arrays for existing before trying to read info from them. If your network interface, for example, doesnt have gateway (empty lines in config) then your program will stop running at second "foreach". Dont exactly know why no exception happens. Corrected code works fine with my config. Also i removed filling your richbox with DeviceID number at the beginning of this function and added clearing listbox before adding new items.

I'd advise you to try WMI Explorer (http://www.ks-soft.net/hostmon.eng/wmi/index.htm). You will able to see difference in network settings. Hope it will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜