最容易阅读的文本文件的方式是由另一应用程序锁定 [英] Easiest way to read text file which is locked by another application
问题描述
我一直在使用File.ReadAllText抓住一些CSV,但每次我忘记关闭Excel中的文件时,程序会抛出异常,因为它无法访问该文件。
I've been using File.ReadAllText to grab some csv, but every time I forget to close the file in Excel, the application throws an exception because it can't get access to the file.
(好像疯了,我的意思是阅读ReadAllText似乎非常清楚)
(Seems crazy to me, I mean the READ in ReadAllText seems pretty clear)
我知道有File.Open所有花俏,但有不涉及与缓冲区和字符数组乱搞的中间的方法?
I know that there is File.Open with all the bells and whistles, but is there an 'intermediate' method which doesn't involve messing around with buffers and char arrays?
的是的,我很懒,所以投我失望,只是给我的答案第一:)的
推荐答案
我觉得你只是想以下
using (var fileStream = new FileStream("foo.bar", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var textReader = new StreamReader(fileStream))
{
var content = textReader.ReadToEnd();
}
的
FileAccess.Read
参数是什么是重要的,以表明你只想读文件。当然,即使这样做,该文件必须已经用Excel打开中的读取股的模式(参见.NET中的文件共享
枚举) 。我没有测试过,所以我不能保证Excel中做到这一点,但我希望它。
The FileAccess.Read
parameter is what is important, to indicate that you only want to read the file. Of course, even to do this, the file must have been opened by Excel in read-share mode (see the FileShare
enum in .NET). I haven't tested, so I can't guarantee that Excel does this, though I would expect it does.
这篇关于最容易阅读的文本文件的方式是由另一应用程序锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!