Fastest way to read file length C#

jpints14 picture jpints14 · Feb 7, 2012 · Viewed 17.5k times · Source

I am using fs.Length, where fs is a FileStream.

Is this an O(1) operation? I would think this would just read from the properties of the file, as opposed to going through the file to find when the seek position has reached the end. The file I am trying to find the length of could easily range from 1 MB to 4-5 GB.

However I noticed that there is a FileInfo class, which also has a Length property.

Do both of these Length properties theoretically take the same amount of time? Or does is fs.Length slower because it must open the FileStream first?

Answer

ken2k picture ken2k · Feb 7, 2012

The natural way to get the file size in .NET is the FileInfo.Length property you mentioned.

I am not sure Stream.Length is slower (it won't read the whole file anyway), but it's definitely more natural to use FileInfo instead of a FileStream if you do not plan to read the file.


Here's a small benchmark that will provide some numeric values:

private static void Main(string[] args)
{
    string filePath = ...;   // Path to 2.5 GB file here

    Stopwatch z1 = new Stopwatch();
    Stopwatch z2 = new Stopwatch();

    int count = 10000;

    z1.Start();
    for (int i = 0; i < count; i++)
    {
        long length;
        using (Stream stream = new FileStream(filePath, FileMode.Open))
        {
            length = stream.Length;
        }
    }

    z1.Stop();

    z2.Start();
    for (int i = 0; i < count; i++)
    {
        long length = new FileInfo(filePath).Length;
    }

    z2.Stop();

    Console.WriteLine(string.Format("Stream: {0}", z1.ElapsedMilliseconds));
    Console.WriteLine(string.Format("FileInfo: {0}", z2.ElapsedMilliseconds));

    Console.ReadKey();
}

Results:

Stream: 886
FileInfo: 727