Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .NET's FileInfo.Length property lazy?

The following code generates a FileNotFoundException (using .NET 2.0):

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace LazyFileInfoTest
{
    class Program
    {
        static void Main(string[] args)
        {
            File.WriteAllText("Test.txt", "Hello World!");

            DirectoryInfo di = new DirectoryInfo(".");

            FileInfo[] files = di.GetFiles();

            File.Delete("Test.txt");

            foreach (FileInfo fi in files)
            {

                Console.WriteLine(string.Format("{0} Last Modified: {1}", fi.Name, fi.LastWriteTime));
                Console.WriteLine(string.Format("{0} Last Modified: {1}", fi.Name, fi.LastAccessTime));
                //Exception when we reach test.txt
                Console.WriteLine(string.Format("{0} length is: {1}", fi.Name, fi.Length));
            }
        }
    }
}

It looks like the Length property is lazy. Is there any reason why? This seems like an inconsistency because it is not the case with other properties. (See .NET FileInfo.LastWriteTime & FileInfo.LastAccessTime are wrong for a counter example.)

Thanks.


1 Answers

From the docs for FileInfo.Length:

When first called, FileInfo calls Refresh and caches information on the file. On subsequent calls, you must call Refresh to get the latest copy of the information.

That seems to be correct - it looks like it's the other properties being eager which violates their documentation.

like image 71
Jon Skeet Avatar answered Jan 25 '26 19:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!