Lock file for writing/deleting while allowing any process to read

Viewed 30170

I am developing an application in C# (.NET), and am having trouble dealing with file locking.

  • My main application (A) needs read/write access to a certain file.
  • A separate application (B) needs read access to the same file.
  • I need to prevent the user from editing or deleting the file while my application (A) is running. The application (A) is long-running. The file must not be deleted while (A) is running, even when it is not actively being read from or written to.

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?

4 Answers

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);
Related