111,098
社区成员




string strURL = "http://avatar.profile.csdn.net/4/1/A/2_yingkk.jpg";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
System.Drawing.Image img = System.Drawing.Image.FromStream(req.GetResponse().GetResponseStream());
img.Save("c:\\1.jpg");
MemoryStream stream = new MemoryStream(downloadData(tb_url.Text));
Image img= Image.FromStream(stream);
private byte[] downloadData(string url)
{
byte[] downloadedData = new byte[0];
try
{
//Optional
this.lb_status.Text = "Connecting...";
Application.DoEvents();
//Get a data stream from the url
WebRequest req = WebRequest.Create(url);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
//Download in chuncks
byte[] buffer = new byte[1024];
//Get Total Size
int dataLength = (int)response.ContentLength;
//With the total data we can set up our progress indicators
this.lb_status.Text = "Downloading...";
Application.DoEvents();
//Download to memory
//Note: adjust the streams here to download directly to the hard drive
MemoryStream memStream = new MemoryStream();
while (true)
{
//Try to read the data
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
Application.DoEvents();
break;
}
else
{
//Write the downloaded data
memStream.Write(buffer, 0, bytesRead);
}
}
//Convert the downloaded stream to a byte array
downloadedData = memStream.ToArray();
//Clean up
stream.Close();
memStream.Close();
}
catch (Exception)
{
//May not be connected to the internet
//Or the URL might not exist
MessageBox.Show("There was an error accessing the URL.");
}
this.lb_status.Text = "Download Data through HTTP";
return downloadedData;
}
void DownLoadToFile(string Url, string Path)
{
WebRequest HWR = WebRequest.Create(Url);
WebResponse HWRr = HWR.GetResponse();
Stream SR = HWRr.GetResponseStream();
FileStream S = File.Open(Path, FileMode.Create);
byte[] by = new byte[1024];
int o=1;
while (o > 0)
{
o = SR.Read(by, 0, 1024);
S.Write(by, 0, o);
}
S.Close();
SR.Close();
S.Dispose();
SR.Dispose();
HWR = null;
HWRr = null;
}