C# Files

Read and write files with File.

✍️ 2 exercises in this lesson

The static System.IO.File class handles common file tasks:

  • File.WriteAllText(path, text) and File.AppendAllText()
  • File.ReadAllText(path) and File.ReadAllLines(path)
  • File.Exists(path), File.Delete(path)
  • Async versions exist: File.ReadAllTextAsync().

Key Takeaways: C# Files

Mastering C# Files helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C# Files Code Example

C#
string path = "notes.txt";
File.WriteAllText(path, "Learn C#\n");
File.AppendAllText(path, "Build APIs\n");

foreach (var line in File.ReadAllLines(path))
{
    Console.WriteLine($"> {line}");
}

File.Delete(path);
Console.WriteLine(File.Exists(path));
Output
> Learn C#
> Build APIs
False
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C# Files Practice Exercises

Check what you learned in “C# Files”.

/ 2 solved
Fill in the blank

Read all lines of a file.

var lines = File.("notes.txt");
✓ Correct! Not quite. Try again.
Multiple choice

Which class has static methods like WriteAllText?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services