简体   繁体   English

File.ReadLines没有锁定它?

[英]File.ReadLines without locking it?

I can open a FileStream with 我可以打开一个FileStream

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

Without locking the file. 没有锁定文件。

I can do the same with File.ReadLines(string path) ? 我可以用File.ReadLines(string path)做同样的事情吗?

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); 不...如果你看一下Reflector,你会看到最后File.ReadLines打开一个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) (它在技术上打开了一个带有FileStreamStreamReader ,如上所述)

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). 这将返回一个IEnumerable<string> (如果文件有数千行,你只需要一次解析一个就更好了)。 If you need an array, call it as ReadLines("myfile").ToArray() using LINQ. 如果需要一个数组,请使用LINQ将其称为ReadLines("myfile").ToArray()

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) 请注意,从逻辑上讲,如果文件“在它的后面(方法)后面”,那么一切如何工作都是非常不确定的(它可能是技术上定义的,但定义可能很长很复杂)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM