Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program For Reading Data From Stream and Cast Data to Chars

  • Last Updated : 01 Nov, 2021

Given data, now our task is to read data from the stream and cast data to chars in C#. So to do this task we use the following class and methods:

  • FileStream: It is a class that is used to read and write files. So, to manipulate files using FileStream, you need to create an object of FileStream class. 

Syntax:

Stream object = new FileStream(path, FileMode.Open)

Where path is the location of your file – @”c:\A\data.txt” and FileMode is the mode of the file like reading and writing.

  • ReadByte(): This method is used to read the data from the file Byte by Byte. This method will throw NotSupportException when the current stream did not support reading. If the current stream is closed then this method will throw ObjectDisposedException.

Syntax:

FileStream_object.ReadByte()

Example:

Let us consider a file named “file.txt” is present in the A folder of C drive like as shown in the below image:

Now we read data from stream and cast data to chars. So to this follow the following approach.

Approach

  • Read the file named “file.txt” using FileStream with the help of specified path.
  • Read the data in file byte by byte using ReadByte() method until it reaches end of file.
while ((obj = s.ReadByte()) != -1)
{

    // Convert the data into chars and display
    Console.Write("{0} ", (char)obj);
}
  • Display file data into chars using Casting to char.
(char)obj

C#




// C# program to read the data from stream
// and cast data to chars 
using System;
using System.IO;
  
public sealed class GFG{
      
public static void Main()
{
      
    // Read the file from the specified path
    using (Stream s = new FileStream(@"c:\A\file.txt", FileMode.Open))
    {
        int obj;
          
        // Read the data in file byte by byte
        // Using ReadByte() method
        while ((obj = s.ReadByte()) != -1)
        {
              
            // Convert the data into chars and display
            Console.Write("{0} ", (char)obj);
        }
        Console.ReadLine();
    }
}
}

Output:

T H I S  I S  F I L E  D E M O

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!