锁定文件进行写入/删除,同时允许任何进程读取 [英] Lock file for writing/deleting while allowing any process to read
问题描述
我发展在C#(.NET)的应用程序,并且我有处理文件锁定的麻烦。
I am developing an application in C# (.NET), and am having trouble dealing with file locking.
- 在我的主要应用程序(一)需要读/写访问某个文件。
- 在一个单独的应用(二)需要读取相同的文件。
- 我需要prevent从编辑用户或删除文件,而我的应用程序(A)正在运行。应用程序(A)是长期运行。该文件不能被同时删除(A)的运行过程中,即使当它不被积极地读取或写入。
我有完全的控制(一)源和(B),这样我就可以修改它们的任何
I have full control of the source of (A) and (B), so I can modify either of them.
我如何阻止用户从修改/删除应用程序时(A)正在运行的文件,同时允许应用程序(一)读/写,并应用(B)来读取?
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?
推荐答案
使用 FileShare.Read
只允许从其他应用程序读取。您可以通过让应用程序中的运行时流打开锁定文件。你需要一个 NonClosingStreamWrapper
,以避免处理流,当你处理你的的StreamWriter
(自动发生这种情况与使用
)
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
按乔恩斯基特可以从的这里
当应用程序启动使用此锁定文件
When application starts use this to lock the file
FileStream fileStream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
当写入文件使用
using (StreamWriter sr = new StreamWriter(new NonClosingStreamWrapper(fileStream)))
{
// File writing as usual
}
当应用程序结束使用此来释放文件
When application ends use this to release the file
fileStream.Close();
这篇关于锁定文件进行写入/删除,同时允许任何进程读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!