C# FileStream Length, Get Byte Count From File

FileStream Length. The FileStream type has a Length property. We test whether this is accurate and efficient. We look at an example of using Length on FileStream. And then we benchmark the property.FileStreamStream

Note: FileStream has a Length property that returns the byte count. This property is not cached in memory. It is an IO operation.

Example. FileStream has a Length property that will return the length of a file in bytes. This is bytes, not chars, meaning some Unicode strings will have different lengths. The example writes the length of a text file using the Length property.

OpenRead: We open the FileStream using the return value of File.OpenRead, a method that works the same as "new FileStream()" with certain parameters.

Using: This statement ensures correct destruction of the system resources. Using can solve nasty bugs regarding unavailable disk resources.


Length: The example accesses the Length property. This property is slow to access, about equivalent in speed to an actual Read.

Finally: The length of the file is written to the Console. The size of a 35-byte file was correctly written by the program.

C# program that uses Length of FileStream using System; using System.IO; class Program { static void Main() { // Open existing text file with File.OpenRead using (FileStream fileStream = File.OpenRead("TextFile1.txt")) { // Use Length property to get number of bytes long length = fileStream.Length; // Write length to console Console.WriteLine("Length: {0}", length); } } }
Benchmark. In the C# language, properties like Length are conventionally thought to be fast to access. However, the Length property on FileStream is slow and takes as long as an actual Read or ReadByte.

Here: Accessing Length in addition to a Read doubles the time required. This indicates that Length is accessing the disk each time.

FileStream loop that uses Length: C# using (FileStream fs = File.OpenRead("Program.cs")) { for (int i = 0; i < m; i++) { long len = fs.Length; fs.ReadByte(); } } FileStream loop that avoids Length: C# using (FileStream fs = File.OpenRead("Program.cs")) { for (int i = 0; i < m; i++) { fs.ReadByte(); } } Benchmark results FileStream Length used: 413 ms [faster] FileStream alone: 230 ms
Summary. We saw the basics of using Length on streams, and validated our code by checking the file in the file manager. Finally, we saw that using Length on FileStream is about as slow as doing a Read.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to