使用webclient下载文件 [英] Dowloading file using webclient
本文介绍了使用webclient下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的所有人,
我正在尝试从网页地址下载zip文件。为此,我使用webclient概念。当我第一次下载文件时它工作正常。但是下次下载的文件是0KB。如果我出错了,请尽快帮忙。
为了您的信息,我在此提供了几行供您参考。
Dear All,
I am trying to download zip files from a webaddress. For that I am using webclient concept. When I download the file for the first time it works fine. But for the next time the file downloaded was with 0KB. Where I am going wrong please help ASAP.
For your information, I hereby provided few lines for your reference.
_WC = New System.Net.WebClient
If System.IO.Directory.Exists(fDownloads) Then
If System.IO.File.Exists(fDownloads & "\" & cellval) Then
System.IO.File.Delete(fDownloads & "\" & cellval)
_WC.DownloadFileAsync(New Uri(strWebAddress & "/itrol/" & cellval), fDownloads & "\" & cellval, cellval)
System.Threading.Thread.Sleep(1500)
Else
'_WC.DownloadFileAsync((strWebAddress & "/itrol/" & cellval), fDownloads & "\" & cellval, cellval)
_WC.DownloadFileAsync(New Uri(strWebAddress & "/itrol/" & cellval), fDownloads & "\" & cellval, cellval)
System.Threading.Thread.Sleep(1500)
End If
Else
System.IO.Directory.CreateDirectory(fDownloads)
_WC.DownloadFileAsync(New Uri(strWebAddress & "/itrol/" & cellval), fDownloads & "\" & cellval, cellval)
System.Threading.Thread.Sleep(1500)
End If
_WC.CachePolicy = New System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore)
_WC.CancelAsync()
_WC.Dispose()
_WC = Nothing
推荐答案
如果启动文件下载异步,则应处理DownloadFileCompleted
事件。异步下载意味着您希望在另一个线程中执行该任务,而不是等待它完成。因此,你必须处理这个事件,以便在完成后进一步推进该工作。线程睡眠并不能保证你的下载会在那个睡眠时间内完成,就像你的情况一样。
If you start file download async, then you should handleDownloadFileCompleted
event. async download means that you want to do the task in another thread, not to wait for it to complete. therefore you have to handle this event to progress on that job further when it finished. thread sleep doesn't guarantee that your download will finish in that sleep time, as in your case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace Test_WebClient
{
class Program
{
static void Main(string[] args)
{
try
{
WebClient cl = new WebClient();
// handle event
cl.DownloadFileCompleted += cl_DownloadFileCompleted;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
static void cl_DownloadFileCompleted(object sender,
System.ComponentModel.AsyncCompletedEventArgs e)
{
// do your job
}
}
}
这篇关于使用webclient下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文