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))
	{
		return;
	}
	using (var stream = httpWebResponse.GetResponseStream())
	using (var fileStream = File.OpenWrite(saveFilename))
	{
		var bytes = new byte[4096];
		var read=0;
		do
		{
			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
		Return
	End If
	Using stream = httpWebResponse.GetResponseStream()
		Using fileStream = File.OpenWrite(saveFilename)
			Dim bytes = New Byte(4095) {}
			Dim read = 0
			Do
				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

Please Share us:
Please rate this snippet

One thought on “How to download a image from url in C# and VB.NET

Leave a Reply