Tiaan
Tiaan

Reputation: 699

Cannot access file after downloading it with Webclient

I have downloaded a zip file using this code from a web server:

client.DownloadFileAsync(url, savePath);

Then, in another method, during the same session I try and extract the file with this method:

ZipFile.ExtractToDirectory(zipPath, extractDir);

This throws the error:

System.IO.IOException: 'The process cannot access the file 
'C:\ProgramData\ZipFile.zip' because it is being used by another process.'

If I restart the program then unzip the file (without redownloading it) it extracts without any problem.

This doesn't make much sense to me because the Webclient client is located in another method and hence should be destroyed...

There is nothing else accessing that file other than the 2 lines of code provided above.

Is there any way to free the file?

Upvotes: 3

Views: 575

Answers (1)

Matt Ghafouri
Matt Ghafouri

Reputation: 1587

You need to extract the files when the download completed, to do this, you need to use DownloadFileCompleted event of webclient

private void DownloadPackageFromServer(string downloadLink)
    {
        ClearTempFolder();
        var address = new Uri(Constants.BaseUrl + downloadLink);

        using (var wc = new WebClient())
        {
            _downloadLink = downloadLink;
            wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
            wc.DownloadFileAsync(address, GetLocalFilePath(downloadLink));
            wc.Dispose();
        }
    }



 private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    { 

        UnZipDownloadedPackage(_downloadLink); 
    }

 private void UnZipDownloadedPackage(string downloadLink)
    {
        var fileName = GetLocalFilePath(downloadLink);

        ZipFile.ExtractToDirectory(fileName, Constants.TemporaryMusicFolderPath);
    }

Upvotes: 3

Related Questions