StreamReader and StreamWriterare classes are inherited from the base class Stream, these classes are used to read and write from a file.
You may go through the File I/O.
C# StreamReader Class
The StreamReader class inherits from TExtReader class. It is used for reading data from a file. The most used method in this class are:
- Close(): It closes the Streamreader object or any resources assosciateed with it.
- Peek(): It returns the next available character but does not consume it.
- Read(): It reads the next characer in input stream and increases the charcter position by one.
- ReadLine(): It reads the line from input stream and returns the data in the form of string.
- Seek(): This method is used to read or write the data at a specific location from a file.
Example: C# program for StreamReader
Let us create a file called sample.text for this example and the following string is present there:
This is a Website.
This is Simple2code.com. Visit again.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | using System; using System.IO; namespace FileProgram { class Program { static void Main(string[] args) { StreamReader sr = new StreamReader("sample.txt"); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } sr.Close(); } } } |
Output: The string present in a sample.text will be displayed on the screen.
This is a Website.
This is Simple2code.com. Visit again.
C# StreamWriter Class
StreamWriter class inherits TextWriter class. it is used to write a series of characters to a stream in a particular format. The most used method in this class are:
- Close(): This methosd closes the current StreamWriter object and all the resources assosciated with it.
- Flush(): It clears all the data from the buffer and write it in the stream associate with it.
- Write(): It is used to write data to a stream.
- WriteLine(): It writes the the data to a stream and adds the newline character at the end of the data.
Example: C# program for StreamWriter
The following program creates a new file and writes data into that file. The data is provided in the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; using System.IO; namespace FileProgram { public class Program { public static void Main(string[] args) { FileStream file = new FileStream("sample.txt", FileMode.Create); StreamWriter sw = new StreamWriter(file); sw.WriteLine("This is Simple2code.com. Visit again."); sw.Close(); file.Close(); Console.WriteLine("The file is created."); } } } |
Output:
The file is created.
After execution, open the newly created file “sample.text”, you will find the following data.
This is Simple2code.com. Visit again.