How to forcefully unlock a file in c#?

13,556

Solution 1

Ended up using PSTools utility, seems to work fine.

Solution 2

You should use the delayed file operations, see How To Move Files That Are Currently in Use ('Move' included delete in this context).

UnlockFile and friends are for file region locking operations, not for file handle locking, see Locking and Unlocking Byte Ranges in Files. Hopefuly there is no API to unlock a locked file handle, that would render locking pretty much useles...

Solution 3

I looked up the call to System.IO.FileStream.Unlock() in RedGates's Reflector and it seems to just call the External call UnlockFile(). The methods are one in the same.

Our current strategy is to put in a delay when we have a reasonable expectation that the file is about to be unlocked, otherwise we error out.

Share:
13,556
alchemical
Author by

alchemical

Thus have I heard: Premature optimization is the root of all evil.

Updated on June 18, 2022

Comments

  • alchemical
    alchemical almost 2 years

    I need to delete a file. Occasionally, the file may be locked, in this case I'd like to unlock it and delete it anyway.

    I've come across two possibilities in the research so far.

    System.IO.FileStream.Unlock

    and

    //unlock file
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern bool UnlockFile(IntPtr handle, int offsetLow, int offsetHi);`  
    

    Will either of these two methods work? If so, could you please provide a sample as I have not gotten either of these to work. Or, is there another better way?

  • earcam
    earcam about 12 years
    Windows file locking is useless - it's so buggy the stale locks are left in place all the time.