How to Delete a File Which Is Locked by Another Process in C#

How do I delete a file which is locked by another process in C#?

Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the MoveFileEx API function to mark the file for deletion upon next reboot.

If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions.

Delete a file being used by another process

In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad flag. One way to do this would be this:

string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();

Although setting BitmapCacheOption.OnLoad works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource property instead of UriSource:

string filename = ...
BitmapImage image = new BitmapImage();

using (var stream = File.OpenRead(filename))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}

How do I close another process to release file locks?

You can use Process class to find that process, forcibly close that program and then delete that file. Something like this...

Process [] proc Process.GetProcessesByName("winword");
proc[0].Kill();

However I wouldn't suggest this because windows also do not delete opened files.

How can I force the deletion of locked files in C#

I think what you are asking for is impossible due to the nature of a lock.

How would you feel if another program could just snatch your files and wipe them as you were reading data?

I believe these unlockers detect the process and try to force it to release it's lock 1 way or another(maybe even shutting their process down).

While this may work for most applications some will be more aggressive (think virus scanners for example).

So maybe you need to ask yourself if you want to increase your chances of getting a lock or if you need to be absolutely sure to get a lock.

Edit:

Assuming you can terminate the locker process and you really want to clear those files(no matter the consequences) you could find the process that holds the lock and shut it down.
In this thread they give a few solutions for tracking which process holds a lock(in c# code) via either handle, win32 dll's or even plan .NET code.

Disclaimer
Be aware that shutting down a process like this will have a terrible impact on the consistency of that program and you might even do more bad then good(suppose it's writing it's status the the database for example and halfway it gets terminated)

Unable to delete file locked by same process -- weird!

To be sure that you're definitely getting rid of all potential locks on the image, you could wrap your code in a using block.

using(Bitmap myBitmap = new Bitmap())
{
//use myBitmap in here
}

Deletion of a file used by another processes

You can use this program to check which process has locked the file you are trying to delete. You will need to kill the process which locked the file in order to be able to delete the file.
Some sample code to kill the process:

    Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";

foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}

Replace the matchPattern with your pattern, you should be able to kill that process which has locked your file.



Related Topics



Leave a reply



Submit