Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何避免Webclient上的0字节文件下载错误_C#_.net_Http_Download_Webclient - Fatal编程技术网

C# 如何避免Webclient上的0字节文件下载错误

C# 如何避免Webclient上的0字节文件下载错误,c#,.net,http,download,webclient,C#,.net,Http,Download,Webclient,使用以下代码下载文件时: WebClient wc = new WebClient(); wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted); wc.DownloadFileAsync("http://path/file, "localpath/file"); 下载过程中出现错误(没有internet连接、找不到文件等) 它在loca

使用以下代码下载文件时:

WebClient wc = new WebClient();
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync("http://path/file, "localpath/file");
下载过程中出现错误(没有internet连接、找不到文件等) 它在localpath/file中分配一个0字节的文件,这会让人非常恼火

有没有办法以干净的方式避免这种情况


(我已经在下载错误上探测了0字节的文件并将其删除,但我认为这不是推荐的解决方案)

如果对
WebClient.DownloadFile
的代码进行反向工程,您将看到
文件流
在下载开始之前就被实例化了。这就是为什么即使下载失败也会创建文件。没有办法修改代码,所以您应该使用另一种方法

有很多方法可以解决这个问题。考虑使用<代码> WebCclipse。下载数据< /代码>而不是<代码> WebCclipse。
WebClient client = new WebClient();

client.DownloadDataCompleted += (sender, eventArgs) =>
{
    byte[] fileData = eventArgs.Result;
    //did you receive the data successfully? Place your own condition here. 
    using (FileStream fileStream = new FileStream("C:\\Users\\Alex\\Desktop\\Data.rar", FileMode.Create))
        fileStream.Write(fileData, 0, fileData.Length);
};

client.DownloadDataAsync(address);
client.Dispose();

好的,我不喜欢这个解决方案100%,因为我必须自己写,但它仍然比我目前的方法好。顺便问一下,如何对编译后的.net代码进行反向工程?