How to lock file

23,256

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.

Share:
23,256
Naruto
Author by

Naruto

Updated on June 14, 2020

Comments

  • Naruto
    Naruto almost 4 years

    please tell me how to lock file in c#

    Thanks

  • MusiGenesis
    MusiGenesis over 14 years
    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 over 14 years
    @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.
  • techno
    techno over 11 years
    @MitchWheat If i open a lot of file streams like this,will this result in memory loss or reduce system performance?