C Sharp FileStream

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# FileStream

C# FileStream class provides a stream for file operation. It can be used to perform synchronous and asynchronous read and write operations. By the help of FileStream class, we can easily read and write data into file.

C# FileStream example: writing single byte into file

Let's see the simple example of FileStream class to write single byte of data into file. Here, we are using OpenOrCreate file mode which can be used for read and write operations.

 
  1. using System;  
  2. using System.IO;  
  3. public class FileStreamExample  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         FileStream f = new FileStream("e:.txt", FileMode.OpenOrCreate);//creating file stream  
  8.         f.WriteByte(65);//writing byte into stream  
  9.         f.Close();//closing stream  
  10.     }  
  11. }  

Output:

A

C# FileStream example: writing multiple bytes into file

Let's see another example to write multiple bytes of data into file using loop.

 
  1. using System;  
  2. using System.IO;  
  3. public class FileStreamExample  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         FileStream f = new FileStream("e:.txt", FileMode.OpenOrCreate);  
  8.         for (int i = 65; i <= 90; i++)  
  9.         {  
  10.             f.WriteByte((byte)i);  
  11.         }  
  12.         f.Close();  
  13.     }  
  14. }  

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

C# FileStream example: reading all bytes from file

Let's see the example of FileStream class to read data from the file. Here, ReadByte() method of FileStream class returns single byte. To all read all the bytes, you need to use loop.

 
  1. using System;  
  2. using System.IO;  
  3. public class FileStreamExample  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         FileStream f = new FileStream("e:.txt", FileMode.OpenOrCreate);  
  8.         int i = 0;  
  9.         while ((i = f.ReadByte()) != -1)  
  10.         {  
  11.             Console.Write((char)i);  
  12.         }  
  13.         f.Close();  
  14.     }  
  15. }  

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ