clamp
clamp

Reputation: 34006

How to avoid the 0-byte file on Webclient download error

When using the following code to download a file:

WebClient wc = new WebClient();
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync("http://path/file, "localpath/file");

and an error occurs during the download (no internet connection, file not found, etc.) it allocates a 0-byte file in localpath/file which can get quite annoying.

is there a way to avoid that in a clean way?

(i already just probe for 0 byte files on a download error and delete it, but i dont think that is the recommended solution)

Upvotes: 2

Views: 5070

Answers (1)

User 12345678
User 12345678

Reputation: 7804

If you reverse engineer the code for WebClient.DownloadFile you will see that the FileStream is instantiated before the download even begins. This is why the file will be created even if the download fails. There's no way to ammend that code so you should cosnider a different approach.

There are many ways to approach this problem. Consider using WebClient.DownloadData rather than WebClient.DownloadFile and only creating or writing to a file when the download is complete and you are sure you have the data you want.

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();

Upvotes: 3

Related Questions