C# FileStream Explained - Reading from the file using FileStream methods
(Page 4 of 5 )
In the following example we are going to read the bytes of the file we just created.
using System;
using System.IO;
namespace MyStreams
{
class Class1
{
public static void Main()
{
try
{
using(FileStream fStream = File.OpenRead("aFile.txt"))
{
Console.WriteLine("Investigating the file
capabilities");
Console.WriteLine("Can Read? {0}", fStream.CanRead);
Console.WriteLine("Can Write? {0}", fStream.CanWrite);
Console.WriteLine("Can Seek? {0}", fStream.CanSeek);
Console.WriteLine("Before we start reading bytes the
current position: {0}",
fStream.Position);
if(fStream.CanRead)
{
// returns the bytes of the file
byte[] bytes = new byte[fStream.Length];
fStream.Read(bytes, 0, bytes.Length);
foreach(byte b in bytes)
{
Console.Write(" {0} ", b);
}
/* This code can be used in place of the above code
* int temp = 0;
while((temp = fStream.ReadByte()) != -1)
{
Console.WriteLine(temp);
}*/
/* This code can be used in place of the above while
statement
* while(fStream.Position < fStream.Length)
{
Console.Write(" {0} ", fStream.ReadByte());
}
* */
}
Console.WriteLine("nAfter we have read the bytes the
current position: {0}",fStream.Position);
Console.ReadLine();
}
}
catch(IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Compile and run the code to get the following screen shot.

As you can see, we have read the bytes of the file (65 66 67 68). Note that there are three ways to read the bytes of the file which you can try. The one I have used for this example is creating a byte array then using the FileStream.Read() method, which accepts three parameters. The array that is used to store the bytes reads from the file and the index of the array at which to begin to store the bytes, then the last parameter states how many bytes you want to read and store into the array. The next foreach statement prints out each byte value stored in the array. Note that I have used the instance property FileStream.Length as the length of the byte array that's used to store the bytes of the file. The Length property returns the size of the file in bytes.
The next commented solution uses a while loop. the FileStream.ReadByte() instance method reads a byte (but returns it as int value), advances the position of the stream by 1 and returns -1 if there are no bytes to return. So the while loop expression (temp = fStream.ReadByte()) != -1) prints out the byte as long as the value assigned by ReadByte() to temp is not -1.
The last solution also uses a while loop, but this time the while loop expression (fStream.Position < fStream.Length) evaluates to true as long as the position of the stream is less than the length of the stream. Note that we have used a using statement with the FileStream instance to ensure an auto call to the FileStream.Close() method.
Next: Use the Seek() method >>
More C# Articles
More By Michael Youssef