C# IO Reading and Writing file in use 错误

标签 c# file-io

我有一个处理缓存文件读写的库。此库由 Windows 服务和同一台计算机上的控制台应用程序的多个实例使用。控制台应用程序在用户登录时运行。

我偶尔会收到 IO 错误,提示缓存文件正在被另一个进程使用。我假设在尝试同时读取和写入的不同应用程序实例和服务之间发生了冲突。

有没有办法在文件正在使用时锁定文件并强制所有其他请求“排队等待”以访问该文件?

    private void SaveCacheToDisk(WindowsUser user) {
        string serializedCache = SerializeCache(_cache);
        //encryt
        serializedCache = AES.Encrypt(serializedCache);

        string path = user == null ? ApplicationHelper.CacheDiskPath() :
            _registry.GetCachePath(user);
        string appdata = user == null ? ApplicationHelper.ClientApplicationDataFolder() :
            _registry.GetApplicationDataPath(user);

        if (Directory.Exists(appdata) == false) {
            Directory.CreateDirectory(appdata);
        }

        if (File.Exists(path) == false) {
            using (FileStream stream = File.Create(path)) { }
        }

        using (FileStream stream = File.Open(path, FileMode.Truncate)) {
            using (StreamWriter writer = new StreamWriter(stream)) {
                writer.Write(serializedCache);
            }
        }
    }

    private string ReadCacheFromDisk(WindowsUser user) {
        //cache file path
        string path = user == null ? ApplicationHelper.CacheDiskPath() :
            _registry.GetCachePath(user);

        using (FileStream stream = File.Open(path, FileMode.Open)) {
            using (StreamReader reader = new StreamReader(stream)) {
                string serializedCache = reader.ReadToEnd();
                //decrypt
                serializedCache = AES.Decrypt(serializedCache);

                return serializedCache;
            }
        }
    }

最佳答案

当然,您可以使用 mutex并仅在持有互斥量时允许访问。

关于C# IO Reading and Writing file in use 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2297067/

相关文章:

c# - 将 HTML 转换为 PDF 发票

c# - Azure 服务总线中继和 http 协议(protocol)

java - 如何从同一个包加载txt文件

java - 使用executorservice控制运行时进程

c# - 以 Task 作为返回值的 EventHandler

c# - 在 Entity Framework 中获取数据

c# - Visual Studio 不断崩溃

mysql - 如何将数据从 SQL append 到现有文件

java - 文件对象和不同的 NetBeans 包

c - 用 C 将字符数组写入文件