C#同步、异步远程下载文件实例
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://www.mozilla.org/images/feature-back-cnet.png";
webclient mywebclient = new webclient();
mywebclient.downloadfile(url,"c:\\temp\\feature-back-cnet.png");
3、异步下载例子
///summary
///异步分析下载
///summary
private void asyncanalyzeanddownload(string url, string savepath)
{
this.uristring = url;
this.savepath = savepath;
#region 分析计时开始
count = 0;
count1 = 0;
freq = 0;
result = 0;
queryperformancefrequency(ref freq);
queryperformancecounter(ref count);
#endregion
using (webclient wclient = new webclient())
{
autoresetevent waiter = new autoresetevent(false);
wclient.credentials = credentialcache.defaultcredentials;
wclient.downloaddatacompleted += new downloaddatacompletedeventhandler(asyncurianalyze);
wclient.downloaddataasync(new uri(uristring), waiter);
waiter.waitone(); 阻止当前线程,直到收到信号
}
}
///summary
///异步分析
///summary
protected void asyncurianalyze(object sender, downloaddatacompletedeventargs e)
{
autoresetevent waiter = (autoresetevent)e.userstate;
try
{
if (!e.cancelled && e.error == null)
{
string dndir = string.empty;
string domainname = string.empty;
string uri = uristring;
获得域名 [url]httpwww.sina.com[url]
match match = regex.match(uri, @((http(s)))+[w-.]+[^]);, regexoptions.ignorecase
domainname = match.value;
获得域名最深层目录 [url]httpwww.sina.commail[url]
if (domainname.equals(uri))
dndir = domainname;
else
dndir = uri.substring(0, uri.lastindexof(''));
dndir += '';
获取数据
string pagedata = encoding.utf8.getstring(e.result);
liststring urllist = new liststring();
匹配全路径
match = regex.match(pagedata, @((http(s)))+((()+[w-.]+()))+[w-.]+.+( + imagetype + )); , regexoptions.ignorecase
while (match.success)
{
string item = match.value;
短路径处理
if (item.indexof(http) == -1 && item.indexof(https) == -1)
item = (item[0] == '' domainname dndir) + item;
if (!urllist.contains(item))
{
urllist.add(item);
imgurllist.add(item);
实时显示分析结果
addlbshowitem(item);
边分析边下载
webrequest hwr = webrequest.create(item);
hwr.begingetresponse(new asynccallback(asyncdownload), hwr);
hwr.timeout = 0x30d40; 默认 0x186a0 - 100000 0x30d40 - 200000
hwr.method = post;
hwr.c;
hwr.maximumautomaticredirections = 3;
hwr.accept =imagegif, imagex-xbitmap, imagejpeg, imagepjpeg, applicationx-shockwave-flash, applicationvnd.ms-excel, applicationvnd.ms-powerpoint, applicationmsword, ;
hwr.accept = imagegif, imagex-xbitmap, imagejpeg, imagepjpeg, ;
iasyncresult iar = hwr.begingetresponse(new asynccallback(asyncdownload), hwr);
iar.asyncwaithandle.waitone();
}
match = match.nextmatch();
}
}
}
finally
{
waiter.set();
#region 分析计时结束
queryperformancecounter(ref count1);
count = count1 - count;
result = (double)(count) (double)freq;
toolstripstatuslabel1.text = 分析完毕!;
toolstripstatuslabel2.text = string.format( 分析耗时{0}秒, result);
application.doevents();
#endregion
分析完毕
isanalyzecomplete = 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);
}
}