Is the .ReadAllLines file lazy loaded when used with LINQ Where?

I would like to know if this code will evaluate to be lazy or will fail in the way I handle the possible exception ReadAllLines()

. I know for sure the proposal Where

has lazy evaluation, but I'm not sure when I use it with ReadAllLines()

. Possible explanation of how and why should be assessed.

File.ReadAllLines Exceptions

var fileLines = File.ReadAllLines(filePath).Where(line =>
{
    line = line.Trim();
    return line.Contains("hello");
});

string search;
try
{
    search = fileLines.Single();
}
catch (Exception exception)
{
    ...log the exception...
}

      

Thank you in advance

+3


source to share


1 answer


File.ReadAllLines

doesn't load, it loads everything into memory.

string[]  allLines = File.ReadAllLines(filePath);

      

If you want to use LINQ lazy execution, you can use instead File.ReadLines

:

var fileLines = File.ReadLines(filePath)
    .Where(line =>
    {
        line = line.Trim();
        return line.Contains("hello");
    });

      

It's also documented :

The methods ReadLines

and ReadAllLines

differ as follows: when you use ReadLines

, you can start enumerating a collection of strings until the entire collection is returned ; when you use ReadAllLines

, you must wait for the entire array of strings to be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.



But please note that you must be careful with it ReadLines

, as you cannot use it twice. If you try to "execute" it a second time, you get ObjectDisposedException

it because the underlying stream has already been deleted. Update This bug appears to be fixed.

This will throw an exception like:

var lines = File.ReadLines(path);
string header = lines.First();
string secondLine = lines.Skip(1).First();

      

You cannot use it to write to the same file as the stream is still open.

File.WriteAllLines(path, File.ReadLines(path)); // exception:  being used by another process.

      

In these cases, it is File.ReadAllLines

more appropriate.

+7


source







All Articles