另一个进程异常使用的文件 [英] File used by another Process Exception

查看:100
本文介绍了另一个进程异常使用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个C#.net应用程序,一个应用程序(比如App1)将数据写入xml文件,第二个应用程序(让我们称之为App2)从同一个xml文件中读取数据并自行更新。 App2持续监视xml文件中的更改,我正在使用FileSystemWatcher。一旦App1完成对文件的写入,App2就会读取更改。我确保我的App2只读取访问权限,但仍有时候我的App1会抛出一个异常,并且

进程无法访问文件'C:\ xmlFile',因为它正被使用另一个过程。这是我在App2中读取文件的代码片段。



I have 2 C# .net applications, One application (lets say App1) writes data to xml file and the second application (lets call it App2) reads data from the same xml file and updates itself. The App2 continuously monitors for the changes in xml file, for which I am using FileSystemWatcher. As soon as the App1 completes writing to the file, the App2 reads the changes. I made sure my App2 is reading the xml only with Read access but still sometime my App1 throws an exception with
"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);
                   }
               }

推荐答案

请看我过去的回答:如何压缩错误'它已被vb.net中的另一个进程'使用 [ ^ ]。



-SA
Please see my past answer: how to compress the error 'it is already used by another process' in vb.net[^].

—SA


这篇关于另一个进程异常使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆