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

时光毁灭记忆、已成空白 提交于 2019-12-03 22:03:36

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.

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.

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

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