Question

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();
Was it helpful?

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?

OTHER TIPS

Use a Global Mutex being very careful to release it (Finally etc.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top