How to save an image (C #) on a webpage to a local computer

Source: Internet
Author: User

 

Using System;
Using System. Net;
Using System. IO;
Using System. Text;

Namespace mynamespace
{
Public class Downloader
{
/// <Summary>
/// Download the image
/// </Summary>
/// <Param name = "picUrl"> Http address of the image </param>
/// <Param name = "savePath"> Save path </param>
/// <Param name = "timeOut"> maximum Request time for a Request. If it is-1, there is no restriction. </param>
/// <Returns> </returns>
Public static bool DownloadPicture (string picUrl, string savePath, int timeOut)
{
Bool value = false;
WebResponse response = null;
Stream stream = null;
Try
{
HttpWebRequest request = (HttpWebRequest) WebRequest. Create (picUrl );
If (timeOut! =-1) request. Timeout = timeOut;
Response = request. GetResponse ();
Stream = response. GetResponseStream ();
If (! Response. ContentType. ToLower (). StartsWith ("text /"))
Value = SaveBinaryFile (response, savePath );
}
Finally
{
If (stream! = Null) stream. Close ();
If (response! = Null) response. Close ();
}
Return value;
}
Private static bool SaveBinaryFile (WebResponse response, string savePath)
{
Bool value = false;
Byte [] buffer = new byte [1024];
Stream outStream = null;
Stream inStream = null;
Try
{
If (File. Exists (savePath) File. Delete (savePath );
OutStream = System. IO. File. Create (savePath );
InStream = response. GetResponseStream ();
Int l;
Do
{
L = inStream. Read (buffer, 0, buffer. Length );
If (l> 0) outStream. Write (buffer, 0, l );
} While (l> 0 );
Value = true;
}
Finally
{
If (outStream! = Null) outStream. Close ();
If (inStream! = Null) inStream. Close ();
}
Return value;
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.