Easiest way to read text file which is locked by a

2019-02-16 04:18发布

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.

(Seems crazy to me, I mean the READ in ReadAllText seems pretty clear)

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?

Yes, I'm lazy, so vote me down, just give me the answer first :)

2条回答
Bombasti
2楼-- · 2019-02-16 04:29

If you want to specify file sharing flags in order to open a file that's in use, you're stuck with File.Open().

查看更多
聊天终结者
3楼-- · 2019-02-16 04:34

I think you just want the following:

using (var fileStream = new FileStream("foo.bar", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var textReader = new StreamReader(fileStream))
{
    var content = textReader.ReadToEnd();
}

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.

查看更多
登录 后发表回答