How to delete a file in use by another process

Here's the deal.

My WinApp works, doesn't it? in let say process' A'.It creates a file and saves a handle (keeps the file open for writing, this is required).
Then it starts another msbuild process, let's call it "B". This process begins with the System.Diagnostic.Process class .
At some point my WinApp (A) has to delete the previously created file (remember that it was created by A himself) and that when I get an IOException with the message "Process cannot access file" X "because it is in use by another process. " And it really is! ... If I terminate process "B", only then can "A" successfully delete the file.

So my questions are:
1) Is there a way that I can tell that the process I am creating is not processing the files I have opened?

2) Is there any other way to achieve my scenario?

0


source to share


4 answers


It looks like System.Diagnostic.Process.Start

calling CreateProcess with the argument bInheritHandles

set to true

.



You can try setting UseShellExecute

to true in ProcessStartInfo or directly P / Invoke to CreateProcess

.

+2


source


It is possible to force a file descriptor to close without closing the process by using the file descriptor, although this may cause the application to crash. In other words, doing what you can do may cause "B" to crash. However, what you are asking is definitely possible, as the Process Explorer application can do it. I'm looking at the post in this link, you might find it informative, although even the action of finding which application is using the handle is an exercise in frustration, it doesn't matter if it actually closes the handle.



0


source


I don't know of a guaranteed way to delete a file with open handles, but if you can wait for a system reboot for the file to be deleted, you can use the same method as the MoveFile utility from Sysinternals.

This program adds registry values ​​to HKLM \ System \ CurrentControlSet \ Control \ Session Manager \ PendingFileRenameOperations a key that Windows checks at boot to ensure that the file is removed, although not immediately.

0


source


I ran into a similar problem when I was trying to read a file that was locked exclusively.

I tried to do it using:

FileStream exclusiveWriter = new FileStream(@"C:\Temp\FileLockTest1.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);  

      

A full discussion is available at:

File locked only by another process - Disconnect from MSDN Forum

Hope it helps.

0


source







All Articles