none
Network Connectivity Caching? RRS feed

  • Question

  •  

    I am developing some logic to determine whether a tablet PC is on or off the network.  The code I have works initially but if I call it again then it returns the same value.  Is network status something that is cached or is my application caching something?  To get the proper connection status I have to stop the application and then start it up again.  I will paste the code below:

     

    Code Snippet

    private void button1_Click(object sender, EventArgs e)

    {

    bool b = false;

    b = IsConnected();

    MessageBox.Show(b.ToString());

    }

    private bool IsConnected()

    {

    bool connected = SystemInformation.Network;

    if (connected)

    {

    connected = false;

    string s = "SELECT NetConnectionStatus FROM Win32_NetworkAdapter";

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(s);

    foreach (ManagementObject networkAdapter in searcher.Get())

    {

    if (networkAdapter["NetConnectionStatus"] != null)

    {

    if (Convert.ToInt32(networkAdapter["NetConnectionStatus"]).Equals(2))

    {

    connected = true;

    break;

    }

    }

    }

    searcher.Dispose();

    }

    return connected;

    }

     

     

     

     

    Wednesday, September 17, 2008 6:11 PM

Answers

  • Just to follow-up on this thread, the problem was that my WMQ was not specific enough.

     

    Set a timer to call this method:

     

    Code Snippet

    private void IsNetworkConnected(object state)

    {

    ManagementObjectSearcher searcher =

    new ManagementObjectSearcher("root\\CIMV2",

    "SELECT NetConnectionStatus FROM Win32_NetworkAdapter WHERE AdapterType = 'Ethernet 802.3'");

    try

    {

    foreach (ManagementObject queryObj in searcher.Get())

    {

    if (queryObj["NetConnectionStatus"] != null)

    {

    if (Convert.ToInt32(queryObj["NetConnectionStatus"]).Equals(2))

    {

    connected = true;

    }

    else

    {

    connected = false;

    }

    SetNetworkStatusIndicator();

    }

    }

    }

    catch (ManagementException e)

    {

    MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);

    }

    finally

    {

    searcher.Dispose();

    }

    }

     

     

    Thursday, September 18, 2008 10:18 PM