读取被另一个应用程序锁定的文本文件的最简单方法
我一直在使用 File.ReadAllText()
打开 CSV 文件,但每次我忘记在 Excel 中关闭该文件时,应用程序都会抛出异常,因为它无法访问该文件。
(对我来说似乎很疯狂,我的意思是 ReadAllText 中的 READ 似乎很清楚)
我知道有 File.Open 具有所有花哨的功能,但是是否有一种“中间”方法,不涉及弄乱缓冲区和字符数组?
I've been using File.ReadAllText()
to open a CSV file, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您只需要以下内容:
FileAccess.Read
参数很重要,它表明您只想读取该文件。当然,即使要做到这一点,文件也必须已由 Excel 以读取共享模式打开(请参阅 .NET 中的 FileShare 枚举)。我还没有测试过,所以我不能保证 Excel 会这样做,尽管我希望它会这样做。[编辑]
这是一个方法版本:
I think you just want the following:
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 theFileShare
enum in .NET). I haven't tested, so I can't guarantee that Excel does this, though I would expect it does.[edit]
Here's a method version:
如果您想指定文件共享标志以打开正在使用的文件,则只能使用 File.Open()。
If you want to specify file sharing flags in order to open a file that's in use, you're stuck with File.Open().