How to lock file

Naruto picture Naruto · Sep 16, 2009 · Viewed 21.5k times · Source

please tell me how to lock file in c#

Thanks

Answer

Mitch Wheat picture Mitch Wheat · Sep 16, 2009

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.