Parsi Coders

نسخه‌ی کامل: برسی وضعیت اتصال به اینترنت
شما در حال مشاهده نسخه آرشیو هستید. برای مشاهده نسخه کامل کلیک کنید.
سلام
چطوری میتونم بفهمم که الان به اینتر نت متصل هستم یا نه؟
Check for internet connection in C#
برسی وضعیت اتصال به اینترنت c#
کد:
/// <summary>
/// Method used to check for internet connectivity by piging
/// varoaus websites and looking for the response.
/// </summary>
/// <returns>True if a ping succeeded, False if otherwise.</returns>
/// <remarks></remarks>
public bool isConnectionAvailable()
{
    //build a list of sites to ping, you can use your own
    string[] sitesList = { "www.google.com", "www.microsoft.com" , "www.psychocoder.net" };
    //create an instance of the System.Net.NetworkInformation Namespace
    Ping ping = new Ping();
    //Create an instance of the PingReply object from the same Namespace
    PingReply reply;
    //int variable to hold # of pings not successful
    int notReturned = 0;
     try
        {
         //start a loop that is the lentgh of th string array we
         //created above
            for (int i = 0; i <= sitesList.Length; i++)
            {
                //use the Send Method of the Ping object to send the
                //Ping request
                reply = ping.Send(sitesList[i], 10);
                //now we check the status, looking for,
                //of course a Success status
                if (reply.Status != IPStatus.Success)
                {
                    //now valid ping so increment
                    notReturned += 1;
                }
                //check to see if any pings came back
                if (notReturned == sitesList.Length)
                {
                    _success = false;
                    //comment this back in if you have your own excerption
                    //library you use for you applications (use you own
                    //exception names)
                    //throw new ConnectivityNotFoundException(@"There doest seem to be a network/internet connection.\r\n
                     //Please contact your system administrator");
                    //use this is if you don't your own custom exception library
                    throw new Exception(@"There doest seem to be a network/internet connection.\r\n
                    Please contact your system administrator");
                }
                else
                {
                    _success = true;
                }
            }
    }
    //comment this back in if you have your own excerption
    //library you use for you applications (use you own
    //exception names)
    //catch (ConnectivityNotFoundException ex)
    //use this line if you don't have your own custom exception
    //library
    catch (Exception ex)
    {
        _success = false;
        _returnMessage = ex.Message;
    }
    return _success;
}

//Example Useage
If(!(isConnectionAvailable))
{
   //then do something
}
{
   //then do something
}