简体   繁体   中英

Console C# check for internet availability and wait until it is not available

I have been searching for the code which will help me if the internet connection breaks in between.

I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.

I got good ans here

    public static void ConnectToPUServer()
    {
        var client = new WebClient();
        while (i < 500 && networkIsAvailable)
        {
            string html = client.DownloadString(URI);
            //some data processing
            Console.WriteLine(i);
            i++;
            URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
        }
        Console.WriteLine("Complete.");
        writer.Close();
   }

    static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
    {
        networkIsAvailable = e.IsAvailable;
        if (!networkIsAvailable)
        {
             Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
        }
        else
        {
             ConnectToPUServer();
        }
    }

This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?

you can use the below mentioned code for it you have to use

using System.Net.NetworkInformation;



public partial class MainWindow : Window
{
    public bool IsAvailable { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
    }

    void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
    {
        IsAvailable = e.IsAvailable;
    }


    private void BrowseButton_Click(object sender, RoutedEventArgs e)
    {
        if (IsAvailable)
        {
            WebBrowser1.Navigate(TextBox1.Text);
        }
        else
        {
            MessageBox.Show("Your Popup Message");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM