C Sharp FileStream

C# FileStream

To provide a stream for the file operation for performing the synchronous and asynchronous read and write operations, the FileStream class is used in C#.

Example: writing a single byte into a file:

using System;  
using System.IO;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        FileStream fs = new FileStream("d:\\file.txt", FileMode.OpenOrCreate); 
        fs.WriteByte(86);
        fs.WriteByte(87);
        fs.WriteByte(88);
        fs.WriteByte(89);
        fs.WriteByte(90);
        fs.Close(); 
    }  
}

Output:

Explanation:

In the above example, we are using the FileStream class to write a single byte of data into a file at a time. All the characters representing the ASCII code starting from 86 to 90 will thus be written on the created file one by one. The OpenOrCreate file mode is used here for performing the reading and writing operations.

Example: writing multiple bytes into a file:

using System; 
using System.IO;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        FileStream fs = new FileStream("d:\\file.txt", FileMode.OpenOrCreate);  
        for (int i = 86; i <= 90; i++)  
        {  
            fs.WriteByte((byte)i);  
        }  
        fs.Close();  
    }  
}

Output:

Explanation:

In the above example, we are writing multiple bytes of data into the file at a time using a loop. All the characters representing the ASCII code starting from 86 to 90 will thus be written on the created file at one go.

Example: reading all bytes from file:

using System;  
using System.IO;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        FileStream fs = new FileStream("d:\\file.txt", FileMode.OpenOrCreate);  
        int i = 0;  
        while ((i = fs.ReadByte()) != -1)  
        {  
            Console.Write((char)i);  
        }  
        fs.Close();  
    }  
}

Output:

Explanation:

In the above example, we are using the FileStream class to read data from the file. A loop is required to be used to read all the bytes because the ReadByte() method of FileStream class returns a single byte.

Please follow and like us:
Content Protection by DMCA.com