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?
FileStream lockStream = new FileStream(path, FileMode.Open, FileAccess.Read);
lockStream.Close();
lockStream.Dispose();
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?