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

后端 未结 4 813
再見小時候
再見小時候 2020-12-28 07:58

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 fil
4条回答
  •  抹茶落季
    2020-12-28 09:01

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

提交回复
热议问题