views:

251

answers:

1
+1  Q: 

How to lock file

Hi,

please tell me how to lock file in c#

Thanks

+12  A: 

Simply open it exclusively:

using (FileStream fs = 
           File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
   // use fs
}

Ref.

Update: In response to comment from poster: According to the online MSDN doco, File.Open is supported in .Net Compact Framework 1.0 and 2.0.

Mitch Wheat
And while you're at it, make sure you don't lose the reference and delay unlocking until the GC non-deterministically releases it - use the IDisposable interface, for instance by wrapping the above statement in a `using` block.
Eamon Nerbonne
Not sure this answers the question. OP is looking for the FileStream.Lock method, which doesn't exist in the compact framework. Lock prevents other processes from modifying the file, but still lets them read it. I think your method would block other processes completely.
MusiGenesis
@MusiGenesis: The poster appears to be asking how to lock a file...
Mitch Wheat
@Eamon Nerbonne: Thanks. I have updated and shall slink away in 'using' shame...;)
Mitch Wheat
@Mitch: and your answer may be exactly what he needs, but if he's trying to find a WinMo way to do what FileStream.Lock does (block write access but not read access, and lock a byte range in the file) then it isn't.
MusiGenesis
hey in winMo file lock option itself not there..i checked :-(
Shadow