C#同步、异步远程下载文件实例

时间:2021-05-20

1、使用HttpWebRequest/HttpWebResonse和WebClient
复制代码 代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();

if (!response.ContentType.ToLower().StartsWith("text/"))
{
//Value = SaveBinaryFile(response, FileName);
byte[] buffer = new byte[1024];
Stream outStream = System.IO.File.Create(FileName);
Stream inStream = response.GetResponseStream();

int l;
do
{
l = inStream.Read(buffer, 0, buffer.Length);
if (l > 0)
outStream.Write(buffer, 0, l);
}
while (l > 0);

outStream.Close();
inStream.Close();
}

2、使用WebClient

复制代码 代码如下:
string url = "http://plete = true;
}
}

/// <summary>
/// 异步接受数据
/// </summary>
/// <param name="asyncResult"></param>
public void AsyncDownLoad(IAsyncResult asyncResult)
{
#region 下载计时开始

if (cfreq == 0)
{
QueryPerformanceFrequency(ref cfreq);
QueryPerformanceCounter(ref ccount);
}

#endregion

WebRequest request = (WebRequest)asyncResult.AsyncState;
string url = request.RequestUri.ToString();
try
{
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream stream = response.GetResponseStream())
{
Image img = Image.FromStream(stream);
string[] tmpUrl = url.Split('.');
img.Save(string.Concat(savePath, "/", DateTime.Now.ToString("yyyyMMddHHmmssfff"), ".", tmpUrl[tmpUrl.Length - 1]));
img.Dispose();
stream.Close();
}
allDone.Set();

//从未下载的列表中删除已经下载的图片
imgUrlList.Remove(url);

//更新列表框
int indexItem = this.lbShow.Items.IndexOf(url);
if (indexItem >= 0 && indexItem <= this.lbShow.Items.Count)
SetlbShowItem(indexItem);
}
catch (Exception)
{
imgUrlList.Remove(url);
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章