I am developing an application in C# (.NET), and am having trouble dealing with file locking.
I have full control of the source of (A) and (B), so I can modify either of them.
How can I stop a user from modifying/deleting a file while application (A) is running, while allowing application (A) to read/write, and application (B) to read?
Right-click a file (or click the ellipses (...)) to open the More Options menu. Click Lock. Choose a duration for the lock. If you choose unlimited, the file will be locked until you unlock it manually.
File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it at a specific time and to prevent reading of the file while it's being modified or deleted.
Step 1. Right-click the file that you need to lock on a Windows computer, select Properties. Step 2. On the Properties window, go to General > Advanced > Check Encrypt contents to secure data.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With