C# 读取文件长度的最快方法
我正在使用 fs.Length
,其中 fs
是 FileStream
。
这是一个 O(1)
操作吗?我认为这只是从文件的属性中读取,而不是通过文件来查找查找位置何时到达末尾。我试图查找的文件长度范围很容易从 1 MB 到 4-5 GB。
但是我注意到有一个 FileInfo
类,它也有一个 Length
属性。
理论上,这两个 Length
属性花费的时间相同吗?或者 fs.Length
是否较慢,因为它必须首先打开 FileStream
?
I am using fs.Length
, where fs
is a FileStream
.
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.
However I noticed that there is a FileInfo
class, which also has a Length
property.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 .NET 中获取文件大小的自然方法是 FileInfo.Length 您提到的属性。
我不确定
Stream.Length
速度较慢(无论如何它都不会读取整个文件),但使用FileInfo
而不是FileStream 肯定更自然
如果您不打算读取该文件。这是一个小基准,将提供一些数值:
结果:
The natural way to get the file size in .NET is the FileInfo.Length property you mentioned.
I am not sure
Stream.Length
is slower (it won't read the whole file anyway), but it's definitely more natural to useFileInfo
instead of aFileStream
if you do not plan to read the file.Here's a small benchmark that will provide some numeric values:
Results:
两者都将访问文件系统元数据而不是读取整个文件。我不知道哪个更有效,根据经验,我会说如果您仅想知道长度(和其他元数据),请使用
FileInfo
- 而如果您无论如何都将文件作为流打开,请使用FileStream.Length
。Both will access the file system metadata rather than reading the whole file. I don't know which is more efficient necessarily, as a rule of thumb I'd say that if you only want to know the length (and other metadata), use
FileInfo
- whereas if you're opening the file as a stream anyway, useFileStream.Length
.