C# Files
Working with files means saving data so it stays around after your program closes, and reading it back later. C# makes this simple through the System.IO namespace, especially the File class, which offers ready-made methods to create, write, read, append, and delete files without any complicated setup.
The File Class
Most file work in C# starts with the File class from the System.IO namespace. It provides static helper methods that handle the common tasks for you. Add using System.IO; at the top of your file so you can call these methods directly.
Writing to a File
File.WriteAllText() takes two arguments: the file name (or full path) and the text you want to save. If the file does not exist, it is created. If it already exists, its contents are replaced.
Creating and writing a file
using System;
using System.IO;
class Program
{
static void Main()
{
string fileName = "greeting.txt";
string content = "Hello from C#!";
File.WriteAllText(fileName, content);
Console.WriteLine("File written successfully.");
}
}
// Output:
// File written successfully.Reading from a File
To read text back, use File.ReadAllText(). It returns the whole file as one string. Before reading, it is smart to check that the file actually exists with File.Exists() so your program does not crash on a missing file.
Reading a file safely
using System;
using System.IO;
class Program
{
static void Main()
{
string fileName = "greeting.txt";
if (File.Exists(fileName))
{
string text = File.ReadAllText(fileName);
Console.WriteLine(text);
}
else
{
Console.WriteLine("That file does not exist.");
}
}
}
// Output (if the file exists):
// Hello from C#!Appending and Deleting
Sometimes you want to add to a file rather than overwrite it. File.AppendAllText() adds text to the end of the file, creating it first if needed. When you are done with a file, File.Delete() removes it. Wrapping these in try-catch keeps your program stable if something goes wrong.
Append text, then clean up
using System;
using System.IO;
class Program
{
static void Main()
{
string fileName = "log.txt";
try
{
File.AppendAllText(fileName, "New log entry\n");
Console.WriteLine("Entry added.");
string all = File.ReadAllText(fileName);
Console.WriteLine(all);
File.Delete(fileName);
Console.WriteLine("File deleted.");
}
catch (IOException ex)
{
Console.WriteLine("Something went wrong: " + ex.Message);
}
}
}
// Output:
// Entry added.
// New log entry
//
// File deleted.- Always add using System.IO; before working with files.
- Use File.Exists() before reading to avoid errors.
- WriteAllText overwrites; AppendAllText adds to the end.
- Wrap file code in try-catch to handle real-world failures.
Exercise: C# Files
Which method reads an entire text file's contents into one string in a single call?