开发者

How to forcefully unlock a file in c#?

开发者 https://www.devze.com 2022-12-20 01:30 出处:网络
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 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 stati开发者_如何学运维c 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?


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


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.


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.


Ended up using PSTools utility, seems to work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号