有没有办法使用静态方法获取 .NET 中文件的大小?
我知道获取文件大小的正常方法是使用 FileInfo 实例:
using System.IO;
class SizeGetter
{
public static long GetFileSize(string filename)
{
FileInfo fi = new FileInfo(filename);
return fi.Length;
}
}
是否有一种方法可以使用静态方法执行相同的操作,而无需创建 FileInfo 实例?
也许我每次想要文件大小时都试图过于吝啬地创建一个新实例,但以尝试计算包含 5000 多个文件的目录的总大小为例。尽管 GC 可能已经过优化,但难道就没有一种方法可以做到这一点,而不必对其进行不必要的征税吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
别担心。首先,.NET 中的分配很便宜。其次,该对象将位于第 0 代,因此应该在没有太多开销的情况下收集它。
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.
别担心。
我发现了一篇博客文章,其中有人测量了 .NET 中对象创建的开销(C# 对象创建时间试验),事实证明,创建 10,000 个对象花费了 0.03 秒,即每个对象 3 µs。从文件系统读取文件长度所需的时间肯定会在这 3 微秒中占据显着的主导地位。
.NET 框架中的许多静态方法在内部创建对象并调用它们的实例方法(您可以通过查看参考源或使用某些反射工具来验证这一点)。您假设静态方法更快。不要做出这样的假设。如果您有两种方法来做同样的事情,测量哪一种更快。
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.
如果您确实非常需要静态方法,请使用本机
GetFileSize
或GetFileSizeEx
API。但请记住,这将需要来自CreateFile
API 的文件句柄。您还可以查看
FileInfo
类的源代码:http://referencesource.microsoft.com/#mscorlib/system/io/fileinfo.cs#4ee673c1a4ecad41
If you really, really need a static method, use the native
GetFileSize
orGetFileSizeEx
API. But keep in mind this will require a handle to the file from theCreateFile
API.You can also view the source of the
FileInfo
class:http://referencesource.microsoft.com/#mscorlib/system/io/fileinfo.cs#4ee673c1a4ecad41