Download source code of a website in C#
With the help of the follwing short C# snippet, you’re able to receive the html code / source of any website as string. Such a function is useful, for example, if you want to parse some information from a website for later use.
Thus the snippet works, you have to add the following two using directives to the header of your source.
using System.Net;
using System.IO;
The function itself looks like this:
public string getHTML(string url)
{
//Create request for given url
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//Create response-object
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Take response stream
StreamReader sr = new StreamReader(response.GetResponseStream());
//Read response stream (html code)
string html = sr.ReadToEnd();
//Close streamreader and response
sr.Close();
response.Close();
//return source
return html;
}
A function call could look like this:
getHTML("http://www.code-bude.net");
If you’ve got suggestions or even problems with the snippet, just write a comment.