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

跟風遠走 提交于 2019-12-05 11:18:02

问题


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?


回答1:


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.




回答2:


Don't worry about it.

  • I've found a blog post of someone who measured the overhead of object creation in .NET (C# Object Creation Time Trials), and, as it turns out, creating 10,000 objects took 0.03 seconds, i.e., 3 µs per object. The time required to read the file length from the file system will surely dominate those 3 microseconds significantly.

  • A lot of static methods in the .NET framework internally create objects and call instance methods on them (you can verify this by looking at the reference source or by using some reflection tool). You assume that a static method is faster. Do not make such assumptions. If you have two ways to do the same thing, measure which one is faster.




回答3:


If you really, really need a static method, use the native GetFileSize or GetFileSizeEx API. But keep in mind this will require a handle to the file from the CreateFile API.

You can also view the source of the FileInfo class:

http://referencesource.microsoft.com/#mscorlib/system/io/fileinfo.cs#4ee673c1a4ecad41



来源:https://stackoverflow.com/questions/7583688/is-there-a-way-to-get-the-size-of-a-file-in-net-using-a-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!