Search code examples
c#win32exception

C# System.ComponentModel.Win32Exception


I have been trying to download a program off of a website and then run said program. When I run it I get the following exception. I am new to C# so please use simple language.

System.ComponentModel.Win32Exception: 'The process cannot access the file because it is being used by another process'

No other process is using this program and should run fine.

        if (restart == "1")
        {
            wc.DownloadFileCompleted += new 
            AsyncCompletedEventHandler(FileDowloadComplete);
            Uri imageurl = new Uri(Website);
            System.Threading.Thread.Sleep(1000);
            wc.DownloadFileAsync(imageurl, "Example.exe");
            System.Threading.Thread.Sleep(1000);
            System.Diagnostics.Process.Start("Example.exe");
            System.Threading.Thread.Sleep(1000);
        }

The download works fine and the program will run if I comment out wc.DownloadFileAsync(imageurl, "Example.exe");


Solution

  • The code has problems. Firstly its using DownloadFileAsync which (as it says) downloads in the background. The code does not get any confirmation that the file has been downloaded - it just sleeps for 1 second and 'hopes' that thats enough time to download the file.

    The code does register a FileDownloadComplete callback, but you havent included the code of that callback in your example; its very likely that its the source of your error. Can you post the complete example.

    Because when you comment out the DownloadFileAsync you say your program runs fine, you must alredy have a copy of Example.exe present on your disk. DownloadFileAsync will overwrite an existing file - but only if its not locked. Whats happening is that the 1 second Sleep is not long enough for the Download to complete; your program then starts the existing Example.exe and locks it, and then the DownloadFileAsync completes and tries to copy the temporary downloaded file over the top of the existing Example.exe which you are already running and have in a locked state.