繁体   English   中英

System.IO.IOException:进程无法访问文件“somefile.txt”,因为它正被另一个进程使用

[英]System.IO.IOException: The process cannot access the file 'somefile.txt' because it is being used by another process

我正在尝试以只读模式打开文件。 该文件由仍在运行的另一个应用程序创建,并且可能由该应用程序保持打开状态。 但是,我可以使用记事本等文本编辑器打开文件。 为什么不能以只读模式从文件中读取?

        string file = @"c:\temp\somefile.txt";
        FileInfo fi = new FileInfo(file);  
        
        int len = (int)fi.Length;

        char[] chars = new char[len];
        var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
        
        int numBytesToRead = (int)fs.Length;
        int numBytesRead = 0;               
        
        using (var sr = new StreamReader(fs))
        {
            int n = sr.Read(chars, numBytesRead, len);
        }

您必须使用接受FileShare参数的FileStream构造函数的重载之一。

基本上,所有打开的文件句柄都必须同意 - 您的FileAccess必须与其FileShare兼容,并且您的FileShare必须与其FileAccess兼容(当然,我在这里使用 .NET 名称,但这些 map 是核心 ZAEA23489CE3AA9B64EZ06EBA24 常见概念到所有程序)。

如果您不知道它正在使用什么访问权限,您似乎可能希望使您的FileShare ReadWrite最大化与其他程序互操作的机会。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM