Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Oct 16, 2022, 5:07 AM EDT
StreamReader and StreamWriter are found in the System.IO namespace. Both classes are useful when you want to read or write character-based data. Both of these classes deal with Unicode characters. StreamReader derives from the Abstract class "TextReader" and StreamWriter derives from "TextWriter".
C# StreamReader is used to read characters to a stream in a specified encoding. StreamReader.Read method reads the next character or next set of characters from the input stream. StreamReader is inherited from TextReader that provides methods to read a character, block, line, or all content.
The following code example creates a StreamReader and reads a file content one line at a time and displays to the console. If there is an exception, the exception is displayed on the console.
using System; using System.IO; using System.Text; class Program { static void Main(string[] args) { // File name string fileName = @"C:\Temp\C#CornerMVPsList.txt"; try { // Create a StreamReader using (StreamReader reader = new StreamReader(fileName)) { string line; // Read line by line while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception exp) { Console.WriteLine(exp.Message); } Console.ReadKey(); } }StreamWriter class in C# writes characters to a stream in a specified encoding. StreamWriter.Write() method is responsible for writing text to a stream. StreamWriter class is inherited from TextWriter class that provides methods to write an object to a string, write strings to a file, or to serialize XML.
public static void WriteToFile() { using (StreamWriter sw = File.CreateText(@"E:\Programming Practice\CSharp\Console\table.tbl")) { sw.WriteLine("Please find the below generated table of 1 to 10"); sw.WriteLine(""); for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { sw.WriteLine("{0}x{1}= {2}",i,j,(i*j)); } sw.WriteLine("=============="); } Console.WriteLine("Table successfully written on file."); } }Note: There are few more method are there to do the same please refer article which written very well by @Mahesh Chand sir.
https://www.c-sharpcorner.com/article/csharp-streamwriter-example/
Toufik El AzzaouiRank #3,804 · 389 reputationPosted Oct 16, 2022, 4:58 AM EDT
Streams are used as an intermediate level between the application and the file.