读取被另一个应用程序锁定的文本文件的最简单方法

发布于 2024-08-04 06:01:17 字数 215 浏览 1 评论 0原文

我一直在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你曾走过我的故事 2024-08-11 06:01:17

我认为您只需要以下内容:

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 中的 FileShare 枚举)。我还没有测试过,所以我不能保证 Excel 会这样做,尽管我希望它会这样做。

[编辑]
这是一个方法版本:

static string ReadAllText(string file)
{
    using var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    using var textReader = new StreamReader(fileStream);
    return textReader.ReadToEnd();
}

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.

[edit]
Here's a method version:

static string ReadAllText(string file)
{
    using var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    using var textReader = new StreamReader(fileStream);
    return textReader.ReadToEnd();
}
心舞飞扬 2024-08-11 06:01:17

如果您想指定文件共享标志以打开正在使用的文件,则只能使用 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().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文