Search code examples
c#portable-class-libraryinternet-connection

How to check an internet connection in a Portable class library


So I would like to check an internet connection in a Portable Class Library.

So far I have used this method GetResponse() in C#

But this doesn't return a boolean value to tell me if I have a connection or not.

So far my code looks like this:

    public static bool CheckForInternetConnection()
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
            request.UseDefaultCredentials = true;
            request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
        }
        catch
        {
            return false;
        }
    }

    private static bool FinishRequest(IAsyncResult result)
    {
        HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

but I get an error on the line with new AsyncCallback() saying FinishRequest has the wrong return type.. How can I do this?

Please bear in mind that this is in a Portable class library so the method GetResponse() does not exist


Solution

  • You could use the manualresetevent like this:

    private static ManualResetEvent evt = new ManualResetEvent(false);
    
    public static bool CheckForInternetConnection()
    {
      try
      {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
        request.UseDefaultCredentials = true;
        request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
        evt.WaitOne();
        return request.HaveResponse;
      }
      catch
      {
        return false;
      }
    }
    
    private static void FinishRequest(IAsyncResult result)
    {
      HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
      evt.Set();
    }