alchemical
alchemical

Reputation: 13995

How to forcefully unlock a file in c#?

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?

Upvotes: 6

Views: 14850

Answers (4)

alchemical
alchemical

Reputation: 13995

Ended up using PSTools utility, seems to work fine.

Upvotes: 1

Dan Blair
Dan Blair

Reputation: 2381

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.

Upvotes: 1

Rubens Farias
Rubens Farias

Reputation: 57996

You could to try to make a P/Invoke call to MoveFileEx and MOVEFILE_DELAY_UNTIL_REBOOT:

The system does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.

Upvotes: 0

Remus Rusanu
Remus Rusanu

Reputation: 294417

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...

Upvotes: 2

Related Questions