Forcing closed an open file by C#

halfbit picture halfbit · Aug 20, 2010 · Viewed 25.5k times · Source

I found a similar question here but it was closed/accepted with an answer of "don't do that".

I'm in a situation where I don't care what happens to the other applications, I want to take a file that may be locked by others (rudely if needed) and have my way with it. I may need to move, rename, or delete this file.

Basically I need to process files in a directory that is created by an app that doesn't clean up it's locks. I know the app is done processing when mine calls, but I need to kill the locks when I run. In addition it seems I'm conflicting with reads from local AV software scanning the remote share where the server is.

All this adds up to an unresolvable "force close" situation so I can do what I need. Does anyone have an idea on what to do?

Answer

SteveCav picture SteveCav · Aug 20, 2010

First you can use this post to verify that it's the dodgy app that's locking them:

How do I find out which process is locking a file using .NET?

Then this post outlines a way to close them:

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/04a1e899-2a38-4d95-8ed5-6d53344e4d76