File IO Operations in C#
File Input/Output (IO) operations are essential for reading from and writing to files in C#. Understanding these operations is crucial for managing data persistence and file manipulation. This guide will explain five key File IO operations in C#.
1. Reading from a File
Reading from a file involves opening a file, reading its contents, and then closing the file. The File.ReadAllText
method is commonly used to read the entire content of a file as a string.
Example
string filePath = "example.txt"; string fileContent = File.ReadAllText(filePath); Console.WriteLine(fileContent);
In this example, the File.ReadAllText
method reads the entire content of "example.txt" and stores it in the fileContent
variable.
2. Writing to a File
Writing to a file involves creating or opening a file, writing data to it, and then closing the file. The File.WriteAllText
method is used to write a string to a file.
Example
string filePath = "output.txt"; string content = "Hello, World!"; File.WriteAllText(filePath, content);
In this example, the File.WriteAllText
method writes the string "Hello, World!" to "output.txt". If the file does not exist, it is created; if it does exist, its content is overwritten.
3. Appending to a File
Appending to a file involves adding new data to the end of an existing file without overwriting its content. The File.AppendAllText
method is used for this purpose.
Example
string filePath = "log.txt"; string newEntry = "New log entry at " + DateTime.Now; File.AppendAllText(filePath, newEntry + Environment.NewLine);
In this example, the File.AppendAllText
method appends a new log entry to "log.txt". If the file does not exist, it is created.
4. Reading Lines from a File
Reading lines from a file involves reading the file line by line. The File.ReadAllLines
method returns an array of strings, where each string represents a line from the file.
Example
string filePath = "data.txt"; string[] lines = File.ReadAllLines(filePath); foreach (string line in lines) { Console.WriteLine(line); }
In this example, the File.ReadAllLines
method reads each line from "data.txt" and stores them in the lines
array.
5. Writing Lines to a File
Writing lines to a file involves writing an array of strings, where each string is written as a separate line in the file. The File.WriteAllLines
method is used for this purpose.
Example
string filePath = "output.txt"; string[] lines = { "Line 1", "Line 2", "Line 3" }; File.WriteAllLines(filePath, lines);
In this example, the File.WriteAllLines
method writes each string in the lines
array as a separate line in "output.txt".