C# provides classes in the System.IO namespace for working with files. This note covers reading and writing text files.
The simplest way to read all lines from a text file is using the File.ReadAllLines() method:
string[] lines = File.ReadAllLines("my_file.txt");
foreach (string line in lines) {
Console.WriteLine(line);
}
For more control, you can use a StreamReader to read the file line by line:
using (StreamReader reader = new StreamReader("my_file.txt")) {
string line;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
The using statement ensures that the StreamReader is properly disposed of, even if exceptions occur.
The easiest way to write all lines to a text file is using File.WriteAllLines():
string[] lines = { "Line 1", "Line 2", "Line 3" };
File.WriteAllLines("output.txt", lines);
For more control, use a StreamWriter:
using (StreamWriter writer = new StreamWriter("output.txt")) {
writer.WriteLine("This is the first line.");
writer.WriteLine("This is the second line.");
// ... more writing ...
}
You can also append to a file using the File.AppendAllText or by opening a `StreamWriter` in append mode:
File.AppendAllText("output.txt", "This line is appended.\n");
using (StreamWriter writer = new StreamWriter("output.txt", true)) { // true for append mode
writer.WriteLine("Another appended line.");
}
Use File.Exists() to check if a file exists before attempting to open it:
if (File.Exists("my_file.txt")) {
// ... read the file ...
} else {
Console.WriteLine("File not found.");
}
using System;
using System.IO;
public class FileIOExample {
public static void Main(string[] args) {
try {
string[] linesToWrite = { "Line 1", "Line 2", "Line 3" };
File.WriteAllLines("my_output.txt", linesToWrite);
if (File.Exists("my_output.txt")) {
string[] readLines = File.ReadAllLines("my_output.txt");
Console.WriteLine("Contents of my_output.txt:");
foreach (string line in readLines) {
Console.WriteLine(line);
}
}
} catch (Exception ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}