File.ReadLines没有锁定它?

Fel*_*oto 14 c# io file stream filestream

我可以打开一个FileStream

new FileStream(logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Run Code Online (Sandbox Code Playgroud)

没有锁定文件.

我可以这样做File.ReadLines(string path)吗?

xan*_*tos 36

不......如果你用Reflector看,你会看到最后File.ReadLines打开一个FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, FileOptions.SequentialScan);

所以只读共享.

(在技术上打开一个StreamReaderFileStream如上所述的)

我将补充说,制作静态方法似乎是孩子的游戏:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会返回一个IEnumerable<string>(如果文件有数千行,你只需要一次解析一个就更好了).如果需要数组,请ReadLines("myfile").ToArray()使用LINQ 调用它.

请注意,从逻辑上讲,如果文件"在它的后面(方法)后面"改变了,那么一切如何工作都是非常不确定的(它可能是技术上定义的,但定义可能很长很复杂)