Locking file for writing from Windows Service
-
27-09-2019 - |
문제
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();
해결책
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?
다른 팁
Use a Global Mutex being very careful to release it (Finally etc.)
제휴하지 않습니다 StackOverflow