views:

148

answers:

1

I do the following:

  1. Copy an executable to C:\temp\x.exe

  2. Start the executable with System.Diagnostics.Process.Start and then wait for the process to exit, synchronously, by calling WaitForExit on the Process object returned by Start.

  3. Delete the executable C:\temp\x.exe

On some machines, this works great, but on others, the call to DeleteFile fails, because the file is still in use. So it seems that once WaitForExit returns, it does not imply that Windows is done with the EXE.

What are my options here? The obvious one whould be to try again the DeleteFile a few milliseconds later, in a loop, until deletion succeeds or the loop times out. But is there a cleaner way to wait for a file to be closed by everyone?

+1  A: 

There's a few reasons way your exe could still be locked when it's done executing. some have to do with your code and some with the system. The two main reasons I can think off for your code would be:

How you close the filestream when you copy the exe file to the temp location, if it's not released explicitly the release timing might change from time to time.

the second is even though the process is done executing doesn't mean it's done in a system perspective.

The first one can be avoid the second can be monitored in the process list BUT you still have a bag of possible locks (your program executing twice in parallel, virus scan some one manually cleaning the temp folder, disc cleanup wizard). So I'd suggest either to rework the logic of the program. If the executeable is written in c# load the binary and execute the program instead of copying the file.

If you for some reason needs to copy the file every time it's executed spawn a low priority cleanup thread. let it try to clean up after the WaitForExit call if that fails make it try again after x milliseconds if that fails again try after 2x and so forth.

That being said I guess their would be (probably unmanaged) API calls to look for file locks on a system level. Personally I would just have the system it self figure that out though

Rune FS
First one has been ruled out; I use CopyFile, nothing fancy there and the handles are properly closed. It must be the OS doing something behind the scenes, shortly after it has shut down the executing process. I implemented the retry loop, but I felt unhappy about it. I suppose this could be an interesting thing to investigate further with tools such as ProcMon.
Pierre