c#读取网页内容流阅读器

本文关键字:读取 网页内容 | 更新日期: 2023-09-27 18:01:51

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

www.example.com

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

i got this:

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

然后我得到这个错误代码

尝试访问方法失败:System.IO.StreamReader . .男星system . string) (

c#读取网页内容流阅读器

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

如果你想使用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;
    }