开发者

File.ReadLines without locking it?

开发者 https://www.devze.com 2023-02-18 13:04 出处:网络
I can open a FileStream with new FileStream(logfileName, FileMode.Open, FileAcces开发者_运维百科s.Read, FileShare.ReadWrite);

I can open a FileStream with

new FileStream(logfileName, FileMode.Open, FileAcces开发者_运维百科s.Read, FileShare.ReadWrite);

Without locking the file.

I can do the same with 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);

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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消