C#阅读网页内容Streamreader

时间:2011-07-11 20:56:10

标签: c# url web streamreader

我需要在streamreader中阅读网页内容,例如

  

www.example.com

<test>
<sample></sample>
</test>

我得到了这个:

System.IO.StreamReader StreamReader1 =
new System.IO.StreamReader("www.example.com");
string test = StreamReader1.ReadToEnd();

但是我得到了这个错误代码

  

尝试访问该方法失败:   System.IO.StreamReader..ctor(System.String)

2 个答案:

答案 0 :(得分:27)

尝试WebClient,它更容易,您不必担心溪流和河流:

using (var client = new WebClient())
{
    string result = client.DownloadString("http://www.example.com");
    // TODO: do something with the downloaded result from the remote
    // web site
}

答案 1 :(得分:4)

如果你想使用StreamReader,这里是我正在使用的代码:

    const int Buffer_Size = 100 * 1024;


        WebRequest request = CreateWebRequest(uri);
        WebResponse response = request.GetResponse();
        result = GetPageHtml(response);

...

    private string GetPageHtml(WebResponse response) {
        char[] buffer = new char[Buffer_Size];
        Stream responseStream = response.GetResponseStream();
        using(StreamReader reader = new StreamReader(responseStream)) {
          int index = 0;
          int readByte = 0;
          do {
              readByte = reader.Read(buffer, index, 256);
              index += readByte;
          }
          while (readByte != 0);
          response.Close();
        }
        string result = new string(buffer);
        result = result.TrimEnd(new char[] {'\0'});
        return result;
    }