Lock file for writing/deleting while allowing any process to read
Most of the time, a locking of the file is not to prevent user deleting the file, but inform user running another instance of the application that the file is "in use" by another user. This is expecially useful if multiple users are opening r/w a file into a shared folder. In such scenario, instead of locking the file at filesystem level, would be much more easier to use a "lock file" generated when Appication (A) opens the file. Thus, any other application, would notice that a lock file exist (you can name it using the same filename but different extension), and also inside the locking file you can write who and when someone have aquired the lock. Application (B) can now respond to user... "The file appear to be under modification by user xxx from machine yyy, do you really want to load it ?"
Of course, the application must remove the lock file when the application file is no longer in use or when the application terminates. In the "unfortunate" case that a crash leave the lock on filesystem, user can just respond yes to the warning request, or can manually delete it to free the lock.
Hope this helps,
Paolo Marani
Use FileShare.Read
to only allow reads from other applications. You can lock the file by having a stream open while the application A runs. You need a NonClosingStreamWrapper
to avoid disposing the stream when you dispose your StreamWriter
(this happens automatically with using
)
NonClosingStreamWrapper
by Jon Skeet can be found from here
Example
When application starts use this to lock the file
FileStream fileStream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
When writing to a file use
using (StreamWriter sr = new StreamWriter(new NonClosingStreamWrapper(fileStream)))
{
// File writing as usual
}
When application ends use this to release the file
fileStream.Close();