0

How to release file that is in use by another program in c#?

if(!IsFileLocked(fileName))
{
    // write in file
}
else
{    
   // first   ReleaseFile(fileName);    
   // two     write in file    
}
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Hossein Hagh
  • 127
  • 2
  • 3
  • 15
  • You can only release the file lock if you (your process/thread) own the file handle. – Sam Axe Nov 05 '13 at 10:42
  • 1
    Due to this article : http://social.msdn.microsoft.com/Forums/vstudio/en-US/9e2044c5-ae5d-4552-a335-01cc567dfc58/how-to-unlock-a-file-used-by-other-process?forum=csharpgeneral , You may first to kill the process who use the file first. – Stefano Bafaro Nov 05 '13 at 10:43
  • @Dan-o: not true, else applications like [Unlocker](http://www.emptyloop.com/unlocker/) wouldn't be possible :-) – Dan Puzey Nov 05 '13 at 10:45
  • 4
    You shouldn't try to control other programs.. – Sayse Nov 05 '13 at 10:48
  • possible duplicate of [How to release a handle through C#?](http://stackoverflow.com/questions/1225945/how-to-release-a-handle-through-c) – sloth Nov 05 '13 at 10:51
  • @DanPuzey: unlocker does some bad things. It is generally not ok to close a handle that doesn't belong to you. – Sam Axe Nov 06 '13 at 02:37
  • @Dan-o: agreed, but it's not impossible, and it seems that's what the OP is asking to do. – Dan Puzey Nov 06 '13 at 08:31

2 Answers2

2

You can't control other processes locking of files in C# natively. Your only option is to use Process.Kill to kill the processes locking the file, assuming you know which processes those are.

Tobberoth
  • 9,327
  • 2
  • 19
  • 17
0

duplicate question How to release a handle through C#?

use PInvoke if you have an handler that you want to close

[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
Community
  • 1
  • 1
lordkain
  • 3,061
  • 1
  • 13
  • 18
  • If it's a duplicate question and you know it, you should not simply copy the answer 1:1 but just flag/vote to close the question as duplicate. – sloth Nov 05 '13 at 10:52