Search code examples
c#windows-servicesfile-locking

Locking file for writing from Windows Service


I want to lock a file for writing from a Windows Service, but so far my attempts to obtain a lock are not working. The same code works from a Console Application, though.

From what I've read, this is because opportunistic locking is not enabled for my service.

How can I prevent a file from being written to by locking it from a service without resorting to registry hacks?

Code to lock:

FileStream lockStream = new FileStream(path, FileMode.Open, FileAccess.Read);

Code to unlock:

lockStream.Close();
lockStream.Dispose();

Solution

  •   using (fs = new FileStream("somefile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
      { }
    

    Have you used the FileShare mode when you open the file for reading or writing?