• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

最快读取文件长度C#的方式

用户头像
it1352
帮助5

问题说明

我使用 fs.Length ,其中 FS 的FileStream

这是一个 O(1)操作?我认为这会从文件的属性只读取,而不是去通过文件找到时,寻求位置已经到达终点。该文件我想找到的长度可以很容易地从1 MB到GB 4-5。

Is this an O(1) operation? I would think this would just read from the properties of the file, as opposed to going through the file to find when the seek position has reached the end. The file I am trying to find the length of could easily range from 1 MB to 4-5 GB.

不过,我注意到,有一个的FileInfo 类,它也有一个长度属性。

However I noticed that there is a FileInfo class, which also has a Length property.

执行这两个长度性能理论上需要的时间是相同的?抑或是 fs.Length 慢,因为它必须先打开的FileStream?

Do both of these Length properties theoretically take the same amount of time? Or does is fs.Length slower because it must open the FileStream first?

正确答案

#1

自然的方式来获得的文件大小 .NET 是你提到的 FileInfo.Length 属性。

The natural way to get the file size in .NET is the FileInfo.Length property you mentioned.

我不知道 Stream.Length 较慢(它不会读取整个文件无论如何),但它肯定更自然的使用的FileInfo ,而不是的FileStream ,如果你不打算读取该文件。

I am not sure Stream.Length is slower (it won't read the whole file anyway), but it's definitely more natural to use FileInfo instead of a FileStream if you do not plan to read the file.

下面是一个小的基准,它会提供一些数值:

Here's a small benchmark that will provide some numeric values:

private static void Main(string[] args)
{
    string filePath = ...;   // Path to 2.5 GB file here

    Stopwatch z1 = new Stopwatch();
    Stopwatch z2 = new Stopwatch();

    int count = 10000;

    z1.Start();
    for (int i = 0; i < count; i  )
    {
        long length;
        using (Stream stream = new FileStream(filePath, FileMode.Open))
        {
            length = stream.Length;
        }
    }

    z1.Stop();

    z2.Start();
    for (int i = 0; i < count; i  )
    {
        long length = new FileInfo(filePath).Length;
    }

    z2.Stop();

    Console.WriteLine(string.Format("Stream: {0}", z1.ElapsedMilliseconds));
    Console.WriteLine(string.Format("FileInfo: {0}", z2.ElapsedMilliseconds));

    Console.ReadKey();
}

结果

Stream: 886
FileInfo: 727

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhbigigc
系列文章
更多 icon
同类精品
更多 icon
继续加载