相关疑难解决方法(0)

如何使用.NET,C#和WPF检查Internet连接

我正在使用.NET,C#和WPF,我需要检查连接是否打开到某个URL,我无法获得我在Internet上找到的任何代码.

我试过了:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    IAsyncResult result = socket.BeginConnect("localhost/myfolder/", 80, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(3000, true);
    if (!success)
    {
        MessageBox.Show("Web Service is down!");
    }
    else
        MessageBox.Show("Everything seems ok");
}
finally
{
    socket.Close();
}
Run Code Online (Sandbox Code Playgroud)

但即使我关闭了我的本地Apache服务器,我总是得到一切都正常的消息.

我也尝试过:

ing ping = new Ping();
PingReply reply;
try
{
    reply = ping.Send("localhost/myfolder/");
    if (reply.Status != IPStatus.Success)
        MessageBox.Show("The Internet connection is down!");
    else
        MessageBox.Show("Seems OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error: " + ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

但这总是给出一个例外(ping似乎只能ping服务器,所以localhost工作但localhost/myfolder/doesnt)

请问如何检查连接,以便它对我有用?

.net c# connection wpf

19
推荐指数
6
解决办法
4万
查看次数

标签 统计

.net ×1

c# ×1

connection ×1

wpf ×1