C# Programming Fundamentals
File I/O Operations
Working with Files
Most applications need to save information. Whether it's user settings, game progress, or a document you've written, data often needs to persist after the program closes. This is where file input and output, or I/O, comes in. C# provides a powerful set of tools for these tasks, mostly found within the System.IO namespace. This namespace is your toolkit for interacting with the computer's file system.
Before you start, make sure to add
using System.IO;at the top of your C# file to easily access the necessary classes.
Writing to a File
The easiest way to write text to a file is by using the StreamWriter class. Think of it as opening a direct line from your program to a text file, allowing you to send strings of text through it.
A crucial practice when working with files is to ensure they are properly closed after you're done. If you don't, the file might remain locked or your data might not be saved correctly. C# makes this easy with the using statement, which automatically closes the file for you, even if errors occur.
using System.IO;
// Specify the path for the new file.
string filePath = "MyFirstFile.txt";
// The 'using' statement ensures the StreamWriter is properly closed.
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, file!");
writer.WriteLine("This is the second line.");
writer.Write("This part is on the ");
writer.Write("same line.");
}
This code creates a file named MyFirstFile.txt in the same directory as your application's executable. The WriteLine() method adds a line of text and then moves to the next line, while Write() adds text without a line break. If the file already exists, this code will overwrite it completely.
Reading from a File
To read text from a file, you'll use the StreamReader class. It works just like StreamWriter but in reverse, opening a channel to pull text from a file into your program.
Again, we'll use a using statement to handle the file properly. A common way to read a file is one line at a time until you reach the end.
using System.IO;
string filePath = "MyFirstFile.txt";
// First, check if the file actually exists.
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
// Read and display lines from the file until the end is reached.
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
This code reads MyFirstFile.txt, which we created earlier. The while loop is a bit clever: reader.ReadLine() reads one line and assigns it to the line variable. The loop continues as long as ReadLine() doesn't return null, which happens when it runs out of lines to read.
For smaller files, you can also use
string content = reader.ReadToEnd();to read the entire file into a single string. Be careful, as this can use a lot of memory for large files.
Managing Files and Directories
Sometimes you need to do more than just read or write. You might need to check if a file exists, delete it, or work with the folders (directories) that contain them. For these tasks, C# provides two very handy static classes: File and Directory. You don't need to create an instance of them; you just call their methods directly.
| Method | Description |
|---|---|
File.Exists(path) | Returns true if the file exists. |
File.Copy(source, dest) | Copies a file from a source to a destination. |
File.Move(source, dest) | Moves a file. Can also be used to rename. |
File.Delete(path) | Deletes a file. |
Directory.Exists(path) | Returns true if the directory exists. |
Directory.CreateDirectory(path) | Creates a new directory. |
Directory.Delete(path) | Deletes an empty directory. |
Directory.GetFiles(path) | Returns an array of file names in a directory. |
Let's see how you might use these to organize files. This example creates a directory, moves our text file into it, and then lists the contents.
using System.IO;
string dirPath = "MyData";
string oldFilePath = "MyFirstFile.txt";
string newFilePath = Path.Combine(dirPath, oldFilePath);
// 1. Create a new directory if it doesn't exist.
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
Console.WriteLine("Directory created.");
}
// 2. Move the file into the new directory.
if (File.Exists(oldFilePath))
{
File.Move(oldFilePath, newFilePath);
Console.WriteLine("File moved.");
}
// 3. List all files in the directory.
if (Directory.Exists(dirPath))
{
Console.WriteLine("Files in directory:");
string[] files = Directory.GetFiles(dirPath);
foreach (string file in files)
{
Console.WriteLine(file);
}
}
Notice the use of Path.Combine(). This is the recommended way to build file paths. It automatically handles the correct path separators (like \ on Windows or / on Linux/macOS), making your code more reliable across different operating systems.
What is the primary C# namespace used for file input and output operations?
Examine the following code. What is the most likely purpose of the while loop?
using (StreamReader reader = new StreamReader("data.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
File operations are a fundamental part of many applications. With these tools, you can store and retrieve data, manage configuration files, and interact with the user's file system in a structured and safe way.