// C # download the image file locally, C #, C #, download the image, download the file, and download the Function
// Download the image from the image address to the local disk
// Save the binary file to the disk
Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. net;
Using system. IO;
Using system. text;
Private void menuitem36_click (Object sender, system. eventargs E)
{
String filename;
String URL;
Filename = "C: // 1.gif ";
Url = "http://www.baidu.com/img/logo-yy.gif ";
If (savephotofromurl (filename, URL )){
MessageBox. Show ("image download succeeded ");
}
Else
{
MessageBox. Show ("image download failed ");
}
}
/// <Summary>
/// Download the image from the image address to the local disk
/// </Summary>
/// <Param name = "tolocalpath"> image local disk address </param>
/// <Param name = "url"> image URL </param>
/// <Returns> </returns>
Public static bool savephotofromurl (string filename, string URL)
{
Bool value = false;
Webresponse response = NULL;
Stream stream = NULL;
Try
{
Httpwebrequest request = (httpwebrequest) webrequest. Create (URL );
Response = request. getresponse ();
Stream = response. getresponsestream ();
If (! Response. contenttype. tolower (). startswith ("text /"))
{
Value = savebinaryfile (response, filename );
}
}< br> catch (exception ERR)
{< br> string AA = err. tostring ();
}< br> return value;
}< BR >///
// save a binary file to disk.
///
/// the response used to save the file
// save the binary file to the disk
Private Static bool savebinaryfile (webresponse response, string filename)
{< br> bool value = true;
byte [] buffer = new byte [1024];
try
{< br> If (file. exists (filename)
file. delete (filename);
stream outstream = system. io. file. create (filename);
stream instream = response. getresponsestream ();
int L;
DO
{< br> L = instream. read (buffer, 0, buffer. length);
If (L> 0)
outstream. write (buffer, 0, L);
}< br> while (L> 0);
outstream. close ();
instream. close ();
}< br> catch
{< br> value = false;
}< br> return value;
}< br>