views:

157

answers:

2

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 http://stackoverflow.com/questions/1448716/net-fileinfo-lastwritetime-fileinfo-lastaccesstime-are-wrong for a counter example.)

Thanks.

+2  A: 

In my opinion, it is correct - the fileInfo object can exist even though there is no such file in the file system! It can still have a name, a directory et cetera. However, when you try to read its length, it needs to be bound to actual item in file system and read the length of file.

UPDATE: Also, from MSDN FileInfo documentation for Length property:

When first called, FileInfo calls Refresh and caches information on the file.

So, refresh needs the file to be in place,otherwise you get an exception.

naivists
+3  A: 

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.

Jon Skeet
Yes, I see it in the docs now. Thanks.
Ragu