How to force unlock file in C #?

I need to delete a file. Sometimes a file may be locked, in which case I would like to unlock it and delete it anyway.

I have found two possibilities in 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 received any of them for work. Or is there any other better way?

+5
source share
4 answers

The end of the use of the PSTools utility seems to work fine.

0
source

, . , ('Move' ).

UnlockFile , , . . Hopefuly API, , useles...

+2

System.IO.FileStream.Unlock() RedGates Reflector , , UnlockFile(). .

, , , - , .

+1

P/Invoke MoveFileEx MOVEFILE_DELAY_UNTIL_REBOOT:

The system does not move the file until the operating system restarts. The system moves the file immediately after executing AUTOCHK, but before creating the swap files. Therefore, this parameter allows the function to delete page files from previous runs.

0
source

All Articles