Hi,

my app needs to have an internet connection to run correctly, so I have been trying to implement a piece of code to check for the availability of a net connection.

private void Form1_Load(object sender, EventArgs e)
        {
            HttpWebRequest req;
            HttpWebResponse resp;
            try
            {
                req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
                resp = (HttpWebResponse)req.GetResponse();

                if (resp.StatusCode.ToString().Equals("OK"))
                {
                    MessageBox.Show("its connected.");
                }
                else
                {
                    MessageBox.Show("its not connected.");
                    Application.Exit();
                }
            }
            catch (Exception exc)
            {
                //Console.WriteLine("its not connected.");
            }}

as you can see this is only basic for testing purposes.

When I run my app with a net connection the message box pops up to say 'it's connected', as it should and the program will carry on.
However, if I turn my net connection off and then run my app, it does not show the 'it's not connected' message and then Exit as it is supposed to do, instead it just runs the app and my main form appears.

Any help or other ways to code this would be welcome.

Kind regards..,

MT ;)

Recommended Answers

All 12 Replies

Import System.Runtime.InteropServices namespace: using System.Runtime.InteropServices; You can use InternetGetConnectedState() API method to get the connection state:

// API Function
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

// A Method for checking the state
public static bool IsConnected()
{
    int Description;
    return InternetGetConnectedState(out Description, 0);
}

Now check for the connection state before creating the WebRequest:

private void Form1_Load(object sender, EventArgs e)
{
    if(IsConnected())
    {
       HttpWebRequest req;
       HttpWebResponse resp;
       try
       {
           req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
           resp = (HttpWebResponse)req.GetResponse();

       }
       catch (Exception exc)
       {
        
       }
    }
    else
      MessageBox.Show("Not connected");
}

[double post]

[double post]

Hi,

thanks for replying.

I cannot seem to get the code to work that you have posted.

I am obviously missing something or not placing the code in the correct places within my form1.cs

I seem to get many errors on missing '}' etc...

Kind regards..,

MT ;)

Check this post at my blog:

http://www.farooqazam.net/csharp-check-if-connected-to-internet/

Thanks

I have looked at your blog but am still having trouble, here is my Forms code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using System.Net;
using System.IO;




namespace K_Component_Tester
{
    public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        // API Function
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        // A Method for checking the state
        public static bool IsConnected()
        {
            int Description;
            return InternetGetConnectedState(out Description, 0);
        }

       private void Form1_Load(object sender, EventArgs e)
        {
            if (isConnected())
            {
                // do something
            }
            else
            {
                MessageBox.Show("Please connect to the internet.");

            }
        }
}
    }

the error I am getting is :-

The name 'isConnected' does not exist in the current context

Kind regards..,

MT ;)

C# is case sensitive! IsConnected != isConnected . Look at your code again.

[Edit] @farooqaaa: Maybe you should edit your blog post!

C# is case sensitive! IsConnected != isConnected . Look at your code again.

Thank you!

That serves me right for just copying and pasting and not looking.

I couldn't see the wood for the trees.

Regards..,

MT ;)

Hi,

OK, it is now working however, I have put

Application.Exit();

in directly after the

MessageBox.Show("Please connect to the internet.");

and it does close the app but for a fraction of a second the Form is shown.

Is there a way to stop this happening?

Kind regards..,

MT ;)

You can put the connection test in the Main subroutine.
That way your form will never even be loaded unless a connection exists.

This worked well when I just tested it.

namespace WindowsApplication1
{
    static class Program
    {
        // API Function
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        // A Method for checking the state
        public static bool IsConnected()
        {
            int Description;
            return InternetGetConnectedState(out Description, 0);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (IsConnected())
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("Please connect to the internet.");
            }
        }
    }
}

Hi,

OK, it is now working however, I have put

Application.Exit();

in directly after the

MessageBox.Show("Please connect to the internet.");

and it does close the app but for a fraction of a second the Form is shown.

Is there a way to stop this happening?

Kind regards..,

MT ;)

Got it.

else
            {
                MessageBox.Show("Please connect to the internet.");
                this.Close();
                Application.Exit();

            }

have to Close the Form before Exiting Application.

Thanks to all who helped.

Regards..,

MT :)

You can put the connection test in the Main subroutine.
That way your form will never even be loaded unless a connection exists.

This worked well when I just tested it.

namespace WindowsApplication1
{
    static class Program
    {
        // API Function
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        // A Method for checking the state
        public static bool IsConnected()
        {
            int Description;
            return InternetGetConnectedState(out Description, 0);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (IsConnected())
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("Please connect to the internet.");
            }
        }
    }
}

Thanks I will have a look at that.

Regards..,

MT ;)

Putting "return;" after Application.Exit(); will also work.

C# is case sensitive! IsConnected != isConnected . Look at your code again.

[Edit] @farooqaaa: Maybe you should edit your blog post!

Sorry, that was a mistake.

Edited the post.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.