简体   繁体   中英

System.Net's Webclient in C# won't connect to server

Is there something I need to do to get System.Net working with Microsoft Visual C# 2008 Express Edition? I can't seem to get any web type controls or classes to work at all.. the below WebClient example always throws the exception " Unable to connect to the remote server ".. and consequently I can't get the WebBrowser control to load a page either.

Here is the code (Edited):

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;
            }
        }
    }
}

This is in a simple form with only a textbox control (with multiline set to true) in it. The exception gets thrown on the DownloadString(...) line. I also tried using WebRequest .. same exception!

EDIT:

I am connected to a Linksys WRT54G Router that connects directly to my cable modem. I am not behind a proxy server, although I did run proxycfg -u and I got:

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

 Direct access (no proxy server).

I am using Windows XP and not running any kind of firewall. Only AVG at the moment. I'm pretty sure I shouldn't have to forward any ports or anything, but I did try forwarding port 80 to my workstation on my router. Didn't help.

( update - I meant proxycfg , not httpcfg ; proxycfg -u will do the import)

First, there is nothing special about "express" here. Second, contoso is a dummy url.

What OS are you on? And do you go through a proxy server? If so, you might need to configure the OS's http stack - proxycfg will do the job on XP, and can be used to import the user's IE settings.

The sample is fine, although it doesn't correctly handle the multiple IDisposable objects - the following is much simpler:

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

Do you have any firewall software on your PC that might be affecting it? Have you tried with any sites other than Google?

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