Download images from a URL in C#

You may use the following method to retrieve the image from a specific URL on the web. The below C# function takes an image url, download the image from the url as a stream and returns an image object. If the image could not be downloaded, it will return null.

public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
    System.Drawing.Image image = null;

        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
        webRequest.AllowWriteStreamBuffering = true;
        webRequest.Timeout = 30000;

        System.Net.WebResponse webResponse = webRequest.GetResponse();

        System.IO.Stream stream = webResponse.GetResponseStream();

        image = System.Drawing.Image.FromStream(stream);

    catch (Exception ex)
        return null;

    return image;

The following code shows how to call the above function to download the image:
protected void btnSave_Click(object sender, EventArgs e)
    System.Drawing.Image image = DownloadImageFromUrl(txtUrl.Text.Trim());

    string rootPath = @"C:\DownloadedImageFromUrl";
    string fileName = System.IO.Path.Combine(rootPath, "test.gif");