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?
The natural way to get the file size in .NET is the FileInfo.Length property you mentioned.
I am not sure
Stream.Lengthis slower (it won’t read the whole file anyway), but it’s definitely more natural to useFileInfoinstead of aFileStreamif you do not plan to read the file.Here’s a small benchmark that will provide some numeric values:
Results: