I need to read the content of a webpage in streamreader like
www.example.com
<test>
<sample></sample>
</test>
开发者_Go百科
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)
Try a 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
}
If you want to use the StreamReader, here is the code I am using:
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;
}
精彩评论