Lesson 40 +10 XP

Working with Files

C

can read from and write to files using classes in the System.IO namespace.

The File class

The File class has methods for creating, reading, writing, and deleting files. To use it, add using System.IO; at the top of your file.

Write to a file


csharp

### File.WriteAllText("filename.txt", "Hello World!");

This creates filename.txt (or overwrites it) with the given text.

Read from a file


csharp
string content = File.ReadAllText("filename.txt");
Console.WriteLine(content);   // Hello World!

Append to a file


csharp

### File.AppendAllText("filename.txt", " More text!");

Delete a file


csharp
if (File.Exists("filename.txt"))
{

### File.Delete("filename.txt");
}

Other common methods

MethodWhat it does
File.Exists(path)true if the file exists
File.Copy(src, dst)copies a file
File.Move(src, dst)moves a file
File.ReadAllLines(path)reads all lines into a string array
File.WriteAllLines(path, lines)writes a string array as lines

Catching errors

If a file doesn't exist and you try to read it, you'll get an exception. In a later module you'll learn to handle that with try...catch.

TL;DR

  • using System.IO; gives you file tools.
  • File.WriteAllText / File.ReadAllText are the basics.
  • File.Exists, File.Delete, File.Copy, File.Move manage files.
  • Missing files throw exceptions - handle them.