I am developing an application in C# (.NET), and am having trouble dealing with file locking.
though I have not used it, but named Mutex
can save your day. Before opening a file in application A, create a mutext like this:
Mutex(bool initiallyOwned, string name, out bool createdNew)
pass file name as second parameter.
now when you open a file in application B, again use Mutex
if out
parameter createdNew
is false then file is already opened by A so you can only read it.
If you only want to lock the file, to prevent writing or deleting, but you don't want to change the file.
I use this to lock a zip file which I use later, so it can be read by others, but can't be altered or changed. If I use the answer of @Cloudanger, I can't read the zip file anymore in other processes.
FileStream fileStreamSslFile = new FileStream(zipFile, FileMode.OpenOrCreate,
FileAccess.Read, FileShare.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
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();