File.ReadLines 没有锁定吗?

发布于 2024-10-23 12:22:17 字数 193 浏览 4 评论 0原文

情况下打开文件流

new FileStream(logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

我可以在不锁定文件的

。我可以用 File.ReadLines(string path) 做同样的事情吗?

I can open a FileStream with

new FileStream(logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

Without locking the file.

I can do the same with File.ReadLines(string path)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

浊酒尽余欢 2024-10-30 12:22:17

不...如果您使用 Reflector 查看,您会发现最终 File.ReadLines 打开一个 FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, FileOptions.SequentialScan);

所以只读共享。

(从技术上讲,它使用 FileStream 打开一个 StreamReader ,如上所述)

我要补充的是,创建一个静态方法来执行此操作似乎是小菜一碟:

public static IEnumerable<string> ReadLines(string path)
{
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
    using (var sr = new StreamReader(fs, Encoding.UTF8))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

这会返回一个IEnumerable (如果文件有数千行并且您一次只需要解析它们,那就更好了)。如果您需要数组,请使用 LINQ 将其调用为 ReadLines("myfile").ToArray()

请注意,从逻辑上讲,如果文件“在(方法的)背后”发生更改,那么一切将如何工作是相当未定义的(它可能是技术上定义的,但定义可能相当长且复杂)

No... If you look with Reflector you'll see that in the end File.ReadLines opens a FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, FileOptions.SequentialScan);

So Read-only share.

(it technically opens a StreamReader with the FileStream as described above)

I'll add that it seems to be child's play to make a static method to do it:

public static IEnumerable<string> ReadLines(string path)
{
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
    using (var sr = new StreamReader(fs, Encoding.UTF8))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

This returns an IEnumerable<string> (something better if the file has many thousand of lines and you only need to parse them one at a time). If you need an array, call it as ReadLines("myfile").ToArray() using LINQ.

Please be aware that, logically, if the file changes "behind its back (of the method)", how will everything work is quite undefined (it IS probably technically defined, but the definition is probably quite long and complex)

拔了角的鹿 2024-10-30 12:22:17

File.ReadLines() 将锁定文件直到完成。

File.ReadLines() will lock the file until it finishes.

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