C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: FileStream has a Length property that returns the byte count. This property is not cached in memory. It is an IO operation.
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.
UsingLength: 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);
}
}
}
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