简体   繁体   English

C# 阅读网页内容 Streamreader

[英]C# Read webpage content Streamreader

I need to read the content of a webpage in streamreader like我需要在流式阅读器中阅读网页的内容,例如

www.example.com 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();

but i then i get this error code但我然后我得到这个错误代码

Attempt to access the method failed: System.IO.StreamReader..ctor(System.String)尝试访问该方法失败:System.IO.StreamReader..ctor(System.String)

Try a WebClient , it's easier and you don't have to worry about streams and rivers:试试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
}

If you want to use the StreamReader, here is the code I am using:如果您想使用 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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM