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
- StreamReader sr = new StreamReader (@"C:/txt.log");
- textBox.Text = sr.ReadToEnd();
- 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
- StreamWriter sw = new StreamWriter(@ "C:\txt.log", false);
- sw.WriteLine("Line1");
- sw.WriteLine("Line2");
- sr.close();
Thanks for reading my blog. Your feedback and comments are welcome.