Alex Rivera | Logout

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

Asked 2010-07-19T07:13:48.987
21

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?

Edit
Report

1 Answer

24

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();
answered 2010-07-19T07:37:33.380

Your Answer