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;
}
}
}