C # Reading Streamreader Web Page Content

I need to read the contents of a webpage in a streamreader, e.g.

www.example.com

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

I got the following:

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

but then i get this error code

Error trying to access the method: System.IO.StreamReader..ctor (System.String)

+5
source share
2 answers

Try WebClient , it’s easier and you don’t have to worry about streams and rivers:

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
}
+26
source

If you want to use StreamReader, here is the code I use:

    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;
    }
+4
source

All Articles