This tutorial is designed to introduce you to the process of reading from and writing to text files in C#. We will be using the StreamReader and StreamWriter classes in C# to accomplish this.
By the end of this tutorial, you will be able to:
Prerequisites
In C#, we use the StreamReader class to read data from a text file, and StreamWriter to write data to a text file.
StreamReader Class
This class comes from the System.IO namespace and is used for reading characters from a byte stream in a particular encoding.
StreamWriter Class
This class is also part of the System.IO namespace and is used to write characters to a stream in a specific encoding.
Example 1: Reading from a Text File
Here's an example of how to read from a text file using StreamReader.
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader("test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Explanation
Example 2: Writing to a Text File
Here's an example of how to write to a text file using StreamWriter.
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("test.txt"))
{
writer.WriteLine("Hello, world!");
}
}
}
Explanation
In this tutorial, we've covered how to read from and write to text files in C# using the StreamReader and StreamWriter classes. We learned that the StreamReader class is used for reading data from a text file and the StreamWriter class is used for writing data to a text file.
For further learning, you could explore the other methods available in these classes, such as ReadToEnd() and Write().
Exercise 1: Write a program that reads a text file and counts the number of lines in the file.
Exercise 2: Write a program that writes the numbers 1 to 10 on separate lines in a text file.
Solutions
Solution to Exercise 1
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader("test.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine("Number of lines: " + lineCount);
}
}
}
In this program, we read each line of the file and increment a counter for each line. The total count is then printed out.
Solution to Exercise 2
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("test.txt"))
{
for(int i=1; i<=10; i++)
{
writer.WriteLine(i);
}
}
}
}
In this program, we use a for loop to write the numbers 1 to 10 on separate lines in the file.