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

2023-09-03 05:49:38 作者:我强大无谓

我使用 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?

推荐答案

自然的方式来获得的文件大小 .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