How To Read And Write Text Files In C#

In the blog, we shall learn how to read and write text files in C#.


What is a File and Stream?

File

A file is a collection of date stored on a disk with a name and often a directory path. When you open a file for reading or writing, it becomes a stream. You can perform read and write operations on a stream.

Stream

Data coming over a network is a stream and we can also create a stream in memory.

In console Applications, keyboard input and text output are also streams.

What class is used to read the data from the files?

We use Stream class to read and write the data. The Stream class is the abstract class, which supports reading and writing bytes.

If our file only contains text, then we can use StreamBuilder or StreamWriter classes.

StreamReader Class

The StreamReader class implements a TextReader, which reads lines of information from a standard text file such as a log file.

A TextReader represents a reader, which can read a sequential series of characters.

Ex 

  1. StreamReader sr = new StreamReader (@"C:/txt.log");  
  2. textBox.Text = sr.ReadToEnd();  
  3. sr.close();   

StreamWriter Class

The StreamWriter Class inherits from the abstract class TextWriter to write the characters to a stream in particular encoding.

The TextWriter class represents a writer, which can write a sequential series of characters.

Eg 

  1. StreamWriter sw = new StreamWriter(@ "C:\txt.log"false);  
  2. sw.WriteLine("Line1");  
  3. sw.WriteLine("Line2");  
  4. sr.close();   

Thanks for reading my blog. Your feedback and comments are welcome.

Ebook Download
View all
Learn
View all