Is there a way to get the size of a file in .NET using a static method?

Will picture Will · Sep 28, 2011 · Viewed 22.6k times · Source

I know the normal way of getting the size of a file would be to use a FileInfo instance:

using System.IO;
class SizeGetter
{
  public static long GetFileSize(string filename)
  {
    FileInfo fi = new FileInfo(filename);
    return fi.Length;
  }
}

Is there a way to do the same thing without having to create an instance of FileInfo, using a static method?

Maybe I'm trying to be overly stingy with creating a new instance every time I want a file size, but take for example trying to calculate the total size of a directory containing 5000+ files. As optimized as the GC may be, shouldn't there be a way to do this without having to tax it unnecessarily?

Answer

Dmitry picture Dmitry · Sep 28, 2011

Don't worry about it. First, allocation in .NET is cheap. Second, that object will be in gen 0 so it should be collected without much overhead.