TExcelTAD
Home › C# › C# Files

C# Files

Programs often need to save data so it survives after they exit: settings, logs, exported reports, game saves. The System.IO namespace contains everything for working with files and folders. The static File class handles the most common tasks in a single method call.

The examples below write to the system's temporary folder (Path.GetTempPath()) and delete their files afterwards, so they are safe to run here and on your own computer.

Writing and reading text

Method What it does
File.WriteAllText(path, text) Creates or overwrites a file with the text
File.AppendAllText(path, text) Adds text to the end (creates the file if needed)
File.ReadAllText(path) Returns the whole file as one string
File.WriteAllLines(path, lines) Writes each string as one line
File.ReadAllLines(path) Returns an array with one string per line
File.Exists(path) true if the file exists
File.Delete(path) Deletes the file (no error if it does not exist)
File.Copy(src, dest) / File.Move(src, dest) Copy or move a file
csharp · try it yourself
using System;
using System.IO;

string path = Path.Combine(Path.GetTempPath(), "exceltad-notes.txt");

File.WriteAllText(path, "First line\n");
File.AppendAllText(path, "Second line\n");
File.AppendAllText(path, "Third line\n");

Console.WriteLine(File.Exists(path));
Console.Write(File.ReadAllText(path));

string[] lines = File.ReadAllLines(path);
Console.WriteLine(
quot;{lines.Length} lines, last: '{lines[^1]}'"); File.Delete(path); Console.WriteLine(File.Exists(path));
True
First line
Second line
Third line
3 lines, last: 'Third line'
False

Path.Combine joins folder and file names with the correct separator for the operating system (\ on Windows, / on Linux and macOS) — always use it rather than gluing strings together.

Working with paths

The Path class manipulates path strings without touching the disk:

csharp · try it yourself
using System;
using System.IO;

string file = Path.Combine("reports", "2024", "sales.final.csv");

Console.WriteLine(Path.GetFileName(file));
Console.WriteLine(Path.GetFileNameWithoutExtension(file));
Console.WriteLine(Path.GetExtension(file));
Console.WriteLine(Path.ChangeExtension(file, ".json").Replace('\\', '/'));
Console.WriteLine(Path.GetDirectoryName(file).Replace('\\', '/'));
sales.final.csv
sales.final
.csv
reports/2024/sales.final.json
reports/2024

A small CSV example

Combine file I/O with string handling to save and reload structured data:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

string path = Path.Combine(Path.GetTempPath(), "exceltad-scores.csv");

var scores = new List<(string Name, double Score)> { ("Mia", 91.5), ("Leo", 78.25), ("Zoe", 85) };

var lines = new List<string> { "name,score" };
foreach (var (name, score) in scores)
    lines.Add(
quot;{name},{score.ToString(CultureInfo.InvariantCulture)}"); File.WriteAllLines(path, lines); double total = 0; foreach (string line in File.ReadAllLines(path)[1..]) // skip the header { string[] parts = line.Split(','); double value = double.Parse(parts[1], CultureInfo.InvariantCulture); total += value; Console.WriteLine(
quot;{parts[0],-4} {value,6:F2}"); } Console.WriteLine(
quot;Average: {total / scores.Count:F2}"); File.Delete(path);
Mia   91.50
Leo   78.25
Zoe   85.00
Average: 84.92

Passing CultureInfo.InvariantCulture guarantees the file always uses a decimal point, even on a computer configured for a language that writes 91,5.

Streams: StreamWriter and StreamReader

The File.ReadAll… methods load the whole file into memory. For large files, or when you want to write piece by piece, use streams. Wrap them in using so the file is closed even if an exception occurs:

csharp · try it yourself
using System;
using System.IO;

string path = Path.Combine(Path.GetTempPath(), "exceltad-log.txt");

using (var writer = new StreamWriter(path))
{
    for (int i = 1; i <= 4; i++)
        writer.WriteLine(
quot;Event {i}: {(i % 2 == 0 ? "OK" : "WARN")}"); } // file is flushed and closed here int warnings = 0; using (var reader = new StreamReader(path)) { string line; while ((line = reader.ReadLine()) != null) { if (line.EndsWith("WARN")) warnings++; Console.WriteLine(line); } } Console.WriteLine(
quot;Warnings: {warnings}"); File.Delete(path);
Event 1: WARN
Event 2: OK
Event 3: WARN
Event 4: OK
Warnings: 2

Directories

The Directory class creates, lists and deletes folders:

csharp
Directory.CreateDirectory("output/images");           // creates every missing folder
string[] csvFiles = Directory.GetFiles("data", "*.csv");
foreach (string dir in Directory.GetDirectories("."))
    Console.WriteLine(dir);
Directory.Delete("output", recursive: true);

Handling errors

File operations can fail for reasons outside your control: the file does not exist, it is locked by another program, or you lack permission. Catch the specific exceptions:

csharp
try
{
    string text = File.ReadAllText("settings.json");
}
catch (FileNotFoundException)
{
    Console.WriteLine("No settings yet - using defaults.");
}
catch (UnauthorizedAccessException)
{
    Console.WriteLine("Permission denied.");
}
catch (IOException ex)
{
    Console.WriteLine(
quot;I/O problem: {ex.Message}"); }

Tip: Every method shown here has an asynchronous twin — File.ReadAllTextAsync, File.WriteAllLinesAsync, StreamReader.ReadLineAsync — for use with await in apps that must stay responsive.

Test yourself

What does File.WriteAllText do if the file already exists?

  1. Appends to it
  2. Throws an exception
  3. Overwrites it
  4. Creates a second copy

Why wrap a StreamWriter in a using statement?

  1. To import the System.IO namespace
  2. To make sure the file is flushed and closed, even if an exception occurs
  3. To write faster
  4. To create the file

Which method builds a path with the correct separator for the operating system?

  1. string.Join
  2. Path.Combine
  3. File.Path
  4. Directory.Join