【发布时间】:2021-02-27 13:17:39
【问题描述】:
我一直在为我的问题寻找解决方案,尝试了很多可能性,但是当文件内容被另一个进程使用时,我仍然无法读取文件内容。我希望有人可以提供帮助:)
using (FileStream fs = File.OpenWrite(file)) //Here I try to simulate that the file is opened for read.
{
Assert.NotNull(xmlUtility.Load(file));
}
这是我想打开它以进行读取访问的代码:
using (StreamReader fs = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
doc = XDocument.Load(fs);
}
【问题讨论】:
-
为什么要使用
OpenWrite来模拟读取?因为 OpenWrite 拒绝来自其他进程的所有访问:check the remarks section in the documentation -
嗯所以基本上这个 File.OpenWrite(file) 使用 FileAccess.None 打开文件,这意味着我无法从任何其他应用程序/代码中打开它吗?
-
完全正确。可能有办法解决它,但您需要第二个应用程序以更多权限运行,并且可能使用另一个 API 来打开文件。
标签: c# ioexception