C#中的System.Net Webclient无法连接服务器

3

我需要在Microsoft Visual C# 2008 Express Edition中使用System.Net,但似乎无法使任何网络类型的控件或类起作用。下面的WebClient示例总是抛出异常“无法连接到远程服务器”,因此我也无法加载WebBrowser控件的页面。

以下是代码(已编辑):

using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            using (WebClient client = new WebClient()) {
                string s = client.DownloadString("http://www.google.com");
                this.textBox1.Text = s;
            }
        }
    }
}

这是一个简单的表单,里面只有一个文本框控件(多行设置为true)。异常在DownloadString(...)行抛出。我还尝试使用WebRequest,但是出现了同样的异常!

编辑:

我连接到Linksys WRT54G路由器,该路由器直接连接到我的电缆调制解调器。我没有在代理服务器后面,虽然我运行了proxycfg -u,结果如下:

Updated proxy settings
Current WinHTTP proxy settings under:
  HKEY_LOCAL_MACHINE\
    SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections\
      WinHttpSettings :

 Direct access (no proxy server).

我正在使用Windows XP,没有运行任何防火墙。目前只有AVG。我相信我不需要转发任何端口或其他东西,但我尝试在我的路由器上将端口80转发到我的工作站上。但并没有帮助。

2个回答

5

(更新 - 我指的是 proxycfg,而不是 httpcfg; proxycfg -u 可以导入)

首先,这里没有什么特别的 "express"。其次,contoso 是一个虚假的 url。

您使用的操作系统是什么?是否通过代理服务器进行访问?如果是的话,您可能需要配置操作系统的 http stack - 在 XP 上可以使用 proxycfg 完成此任务,并可用于导入用户的 IE 设置。

示例很好,尽管它没有正确处理多个 IDisposable 对象 - 以下更简单:

        using (WebClient client = new WebClient()) {
            string s = client.DownloadString("http://www.google.com");
            // do something with s
        }

我正在使用XP系统,没有运行代理服务器。 - Alpants
不过,尝试一下 proxycfg -u 也许是值得的;另外,您是否运行了任何激进的防火墙?请检查是否有任何阻止/拒绝条目... - Marc Gravell

0

你的电脑上有任何可能影响它的防火墙软件吗?你尝试过除了 Google 以外的其他网站吗?


是的,我已经尝试了不同的网站,而且我没有在我的电脑上运行任何防火墙软件。 - Alpants

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接