有没有一种方法可以使用静态方法在.NET中获取文件的大小? [英] Is there a way to get the size of a file in .NET using a static method?

查看:83
本文介绍了有没有一种方法可以使用静态方法在.NET中获取文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道获取文件大小的正常方法是使用FileInfo实例:

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;
  }
}

是否有一种方法可以执行相同的操作而不必使用静态方法创建FileInfo实例?

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

也许每次我想要一个文件大小时,我都试图过分地创建新实例,但是例如,尝试计算包含5000多个文件的目录的总大小.如GC所优化的那样,难道不应该有一种无需不必要地征税就可以做到这一点的方法吗?

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?

推荐答案

不用担心.首先,.NET中的分配很便宜.其次,该对象将出现在gen 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中获取文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆