How to send Data using a WebRequest in C# and VB.NET

To send/post Data using a WebRequest in C# and VB.NET you can use the following snippet.

Sample C#

public static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")
	var postDataAsByteArray = dataEncoding.GetBytes(dataToPost);
	var returnValue = String.Empty;
		var webRequest = WebRequest.CreateHttp(url);  //change to: var webRequest = (HttpWebRequest)WebRequest.Create(url); if you are your .NET Version is lower than 4.5
		if (webRequest != null)
			webRequest.AllowAutoRedirect = false;
			webRequest.Method = "POST";
			webRequest.ContentType = contentType;
			webRequest.ContentLength = postDataAsByteArray.Length;
			using (var requestDataStream = webRequest.GetRequestStream())
				requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length);
				using (var response = webRequest.GetResponse())
					using (var responseDataStream = response.GetResponseStream())
						if (responseDataStream != null)
							using (var responseDataStreamReader = new StreamReader(responseDataStream))
								returnValue = responseDataStreamReader.ReadToEnd();
	catch (WebException ex)
		if (ex.Status == WebExceptionStatus.ProtocolError)
			var response = ((HttpWebResponse)ex.Response);
			//handle this your own way.
			Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}",(int)response.StatusCode,response.StatusDescription);
	catch(Exception ex) 
		//handle this your own way, something serious happened here.
	return returnValue;

Sample VB.NET

Public Shared Function WebrequestWithPost(ByVal url As String, ByVal dataEncoding As Encoding, ByVal dataToPost As String, ByVal contentType As String) As String
    Dim postDataAsByteArray As Byte() = dataEncoding.GetBytes(dataToPost)
    Dim returnValue As String = String.Empty
        Dim webRequest As HttpWebRequest = WebRequest.CreateHttp(url)  'change to: dim webRequest as var = DirectCast(WebRequest.Create(url), HttpWebRequest) if you are your .NET Version is lower than 4.5
        If (Not (webRequest) Is Nothing) Then
            webRequest.AllowAutoRedirect = false
            webRequest.Method = "POST"
            webRequest.ContentType = contentType
            webRequest.ContentLength = postDataAsByteArray.Length
            Dim requestDataStream As Stream = webRequest.GetRequestStream
            requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length)
            Dim response As Webresponse = webRequest.GetResponse
            Dim responseDataStream As Stream = response.GetResponseStream
            If (Not (responseDataStream) Is Nothing) Then
                Dim responseDataStreamReader As StreamReader = New StreamReader(responseDataStream)
                returnValue = responseDataStreamReader.ReadToEnd
            End If
        End If
    Catch ex As WebException
        If (ex.Status = WebExceptionStatus.ProtocolError) Then
            Dim response As HttpWebResponse = CType(ex.Response,HttpWebResponse)
            'handle this your own way.
            Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}", CType(response.StatusCode,Integer), response.StatusDescription)
        End If
    Catch ex As Exception
        'handle this your own way, something serious happened here.
    End Try
    Return returnValue
End Function

FOR MORE INFORMATIONS SEE THE MSDN: How to: Send Data Using the WebRequest Class

How to download a file in Powershell

To download a file in Powershell you can use the following snippet.

Sample Powershell

(New-Object System.Net.WebClient).DownloadFile('', 'C:\Users\MF\Codesnippets\Desktop\Download\npp.6.6.6.Installer.exe')

How to download a website source in Java

To download a website source in Java you can use the following snippet.

Sample Java

private static String getUrlSource(String url) throws IOException {
	URL website = new URL(url);
	URLConnection connection = website.openConnection();
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
	String input;
	StringBuilder strBuilder = new StringBuilder();
	while ((input = bufferedReader.readLine()) != null){
	return strBuilder.toString();

How to download a image from url in C# and VB.NET

Sample C#

private static void DownloadImage(string url, string saveFilename)
	var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
	var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
	if ((httpWebResponse.StatusCode != HttpStatusCode.OK && 
		httpWebResponse.StatusCode != HttpStatusCode.Moved && 
		httpWebResponse.StatusCode != HttpStatusCode.Redirect) 
		|| !httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
	using (var stream = httpWebResponse.GetResponseStream())
	using (var fileStream = File.OpenWrite(saveFilename))
		var bytes = new byte[4096];
		var read=0;
			if (stream == null) {continue;}
			read = stream.Read(bytes, 0, bytes.Length);
			fileStream.Write(bytes, 0, read);
		} while (read != 0);

Sample VB.NET

Private Shared Sub DownloadImage(url As String, saveFilename As String)
	Dim httpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
	Dim httpWebResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
	If (httpWebResponse.StatusCode <> HttpStatusCode.OK AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Moved AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Redirect) OrElse Not httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase) Then
	End If
	Using stream = httpWebResponse.GetResponseStream()
		Using fileStream = File.OpenWrite(saveFilename)
			Dim bytes = New Byte(4095) {}
			Dim read = 0
				If stream Is Nothing Then
					Continue Do
				End If
				read = stream.Read(bytes, 0, bytes.Length)
				fileStream.Write(bytes, 0, read)
			Loop While read <> 0
		End Using
	End Using
End Sub