find and solve || findandsolve.com
Please wait.....

C# FileStream

In the C#, FileStream provides a Stream for a file,supporting both synchronous and asynchronous read and write operations.

By the help of FileStream class, you 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. 

using System; 
using System.IO;
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
           FileStream file = new FileStream("d:\\FileStreamExample.txt", FileMode.OpenOrCreate);//creating file stream            file.WriteByte(65);//writing byte into stream
           file.Close();//closing stream
        }
    }
}

Output

A

C# FileStream example: writing multiple bytes into file

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

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

C# FileStream example: reading all bytes from file

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

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ