Home > database >  Multiple processes in one button
Multiple processes in one button

Time:12-14

First of all hello guys i just wanted to add button that downloads zip files from link and then unzips and i ran into problems i get this error:

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

It looks really simple but i can't solve it so i hope you guys help me. this is code:

    private void button2_Click(object sender, EventArgs e)
    {

        string root = @"C:\GTA";
        //this if directory doesn't exist
        if (!Directory.Exists(root))
        {
            Directory.CreateDirectory(root);
        }

        progressBar1.Value = 0;
        WebClient webcl = new WebClient();
        webcl.DownloadFileCompleted  = Webcl_DownloadFileCompleted;
        webcl.DownloadProgressChanged  = Webcl_DownloadProgressChanged;
        webcl.DownloadFileAsync(new Uri("https://download1474.mediafire.com/17r5hin4vceg/izkb8vk7pudg5g4/TEST.zip"), @"C:\GTA\TEST.zip");

        string targetfolder = @"C:\GTA\UNZIPEDFolder";
        string sourceZipFile = @"C:\GTA\TEST.zip";
        ZipFile.ExtractToDirectory(sourceZipFile, targetfolder);
    } 

CodePudding user response:

I'm no expert here, however you get the file asynchronosly without awaiting it. DownloadFileAsync

So you make a call to extract the file while it's being downloaded.

CodePudding user response:

You calling ExtractToDirectory before file will be actually downloaded, as file downloading is async. So, you need to await when downloading process will finish. To do so, first you will need to make the whole event click handler async - private async void button2_Click(object sender, EventArgs e). Then you will able to await downloading with await webcl.DownloadFileAsync(...args here...);

  • Related