Want to quickly grab a remote web page somewhere using C#? The code snippet below sends a get request to
the URL you specify and returns a string containing the resulting page. If any error occurs it will return an
empty string. You can of course change the catch block to throw any exceptions up to the calling code.
using System.Net;
using System.Text
private string GetWebPage(string url)
{
try
{
HttpWebRequest webRequest =
(HttpWebRequest)WebRequest.Create(url);
webRequest.Timeout = 6000;
HttpWebResponse webResponse =
(HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
string responseEncoding = webResponse.ContentEncoding.Trim();
if (responseEncoding.Length == 0)
responseEncoding="us-ascii";
StreamReader responseReader = new StreamReader(responseStream,
System.Text.Encoding.GetEncoding(responseEncoding));
return(responseReader.ReadToEnd());
}
catch
{
return(string.Empty);
}
}