To get the source of a website in C# and VB.NET you can use the following snippet.

Sample C#

public static string GetHtmlSourceFromUri(string uri)
{
	var retVal = string.Empty;
	var request = (HttpWebRequest)System.Net.WebRequest.Create(uri);
	using (var response = (HttpWebResponse)request.GetResponse())
	{
		bool success = (int)response.StatusCode >= 200 && (int)response.StatusCode < 299;
		if (success)
		{
			var responseStream = response.GetResponseStream();
			if (responseStream != null)
			{
				using (var reader = new StreamReader(responseStream,Encoding.UTF8))
				{
					retVal = reader.ReadToEnd();
				}
			}
		}
	}
	return retVal;
}

Sample Vb.NET

Public Shared Function GetHtmlSourceFromUri(uri As String) As String
	Dim retVal = String.Empty
	Dim request = DirectCast(System.Net.WebRequest.Create(uri), HttpWebRequest)
	Using response = DirectCast(request.GetResponse(), HttpWebResponse)
		Dim success As Boolean = CInt(response.StatusCode) >= 200 AndAlso CInt(response.StatusCode) < 299
		If success Then
			Dim responseStream = response.GetResponseStream()
			If responseStream IsNot Nothing Then
				Using reader = New StreamReader(responseStream,Encoding.UTF8)
					retVal = reader.ReadToEnd()
				End Using
			End If
		End If
	End Using
	Return retVal
End Function

One thought on “How to get the source of a website in C# and VB.NET”

Leave a Reply