且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-08 15:25:28

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