这是一个场景,我有一个应用程序每2秒覆盖一个xml文件.然后我有这个c#应用程序,每1-2秒读取一次该文件.这个过程运行正常,但有时我得到错误说,
进程无法访问文件,因为它由另一个进程使用
我正在使用xmldocument.load打开并读取xml文件.
我该怎么做才能解决这个问题?我试过在不同的机器上运行,这绝对是随机的,就像在我的机器上,它在错误之前运行了6个小时,在另一台机器上,
因为我的c#程序将继续读取此文件,除非用户单击按钮停止数据记录过程
因为我希望程序继续运行,只要用户不停止它.请帮忙
请告诉您是否尝试使用FileStream变量读取XmlDocument内容,该变量使用特定的FileMode和FileAccess以及使用特定指定构造函数的FileShare参数进行实例化.您可以使用Load方法的实现来加载 XmlDocument的内容,该方法需要适当地打开(用于写入具有读取访问权限的共享)文件流作为参数.
请尝试使用以下代码写入文件:
XmlDocument xmlDocument = new XmlDocument();
using (FileStream fileStream = new FileStream("C:\\test.xml", FileMode.Append, FileAccess.Write, FileShare.Read))
{
xmlDocument.Load(fileStream);
}
Run Code Online (Sandbox Code Playgroud)
以及以下代码从文件中读取:
XmlDocument xmlDocument = new XmlDocument();
int attempts = 5;
Exception cannotReadException = null;
while (attempts > 0)
{
try
{
using (FileStream fileStream = new FileStream("C:\\test.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
xmlDocument.Load(fileStream);
attempts = 0;
}
}
catch (Exception exception)
{
cannotReadException = exception;
System.Threading.Thread.Sleep(100);
attempts--;
}
}
if (cannotReadException != null)
{
throw cannotReadException;
}
Run Code Online (Sandbox Code Playgroud)