c# - 另一个进程异常使用的文件

标签 c# xml windows

我有两个 C# .NET 应用程序:

  • 一个应用程序(比方说 App1)将数据写入 XML 文件。
  • 第二个应用程序(我们称它为 App2)从同一个应用程序读取数据 XML 文件并自行更新。

App2 持续监视 XML 文件中的更改,对此我使用 FileSystemWatcher

App1 完成文件写入后,App2 立即读取更改。

我确保我的 App2 仅通过读取访问权限读取 XML,但有时我的 App1 仍会抛出异常:

"The process cannot access the file 'C:\xmlFile' because it is being used by another process". Here is my code snippet in App2 which is reading the file.

这是我的代码:

using (var stream = File.Open(filePath,FileMode.Open,FileAccess.Read))
{
    using (XmlReader reader = XmlReader.Create(stream))
    {
        while (reader.Read())
        {
            // Only detect start elements.
            if (reader.IsStartElement())
            {
                switch (reader.Name)
                {
                    case "Component":
                        fileElements.ComponentName = reader["Name"];
                        fileElements.DateRun = reader["DateRun"];
                        fileElements.Passed = reader["Passed"];
                        break;
                }
            }
        }

        if (filePath.ToLower().Contains("ebsserver"))
        {
            UpdateDataTable1(fileElements);
        }
        else if (filePath.ToLower().Contains("ebsui"))
        {
            UpdateDataTable2(fileElements);
        }
        else
        {
            UpdateDataTable3(fileElements);
        }
    }
}

我该如何解决这个问题?

最佳答案

您必须在阅读应用程序中使用FileShare.ReadWrite 来表示打开时不会锁定。它与文本编辑器中使用的机制相同,例如,打开的文件也被写入。

File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

关于c# - 另一个进程异常使用的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809024/

相关文章:

c# - 如何使用 C# 打开 Putty session

c# - Xamarin Android 抛出错误的 OkHttp 绑定(bind)库

c# - 如何将 XML 文件反序列化为具有只读属性的类?

python - 我可以展平一个深度嵌套的 Python 字典,它包含带有更多嵌套字典列表的值吗?

xml - 在命名空间定义中使用的变量

c++ - WinAPI 函数 LoadLibrary() 导致函数在执行错误期间失败

c# - Int32.Equals 与 '==' 运算符

c# - 如何将属性分配给属性

java - 如何运行 .bat 文件以在运行 .jar 的第二个 .bat 文件中执行命令?

windows - 谁能帮我修复 Windows 10 上的 VBS 脚本,该脚本在电池电量不足时显示警告/MsgBox?