Search code examples
c#locked-files

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


I have a scenario where I must delete a file. I don't know and don't care who holds the file. I must delete it and they can crush for all I care. (I don't want to kill the locking task)

the only solution that comes to my mind is to use http://www.emptyloop.com/unlocker/ command line interface.

MoveFileEx is not and option as I cannot restart the machine.

is there any more C#ish method/library for this?

im not thrilled using console application API

in case it is not clear.I know the risk involved and I don't need a lecture of why this is a bad practice. if you know how to do what I asked. thank you very much!

if you want to lecture why this is bad - just don't find someone else to bother##


Solution

  • 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)