C-SHARP - 5.1 Introduction to section 5

In this section we learn how to work with files and directories in C#. The .NET framework groups every related helper inside the System.IO namespace, which exposes the classes we need to read content, write content and navigate the file system. We start by importing using System.IO; at the top of every file that touches the disk.

Several classes will be useful throughout this chapter. The System.IO namespace itself gives us the high-level building blocks for streaming data and writing or reading bytes. The File class lives inside System.IO and exposes static methods to create, copy, delete, move and open files. The Directory class plays the equivalent role for folders: listing entries, creating, deleting and moving them. We will introduce more helpers as the section moves on.

The classes you will meet

  • File: create, copy, delete, move and open files.
  • Directory: list, create, delete and move folders.
  • StreamReader / StreamWriter: read and write text files line by line.
  • Path: build and combine file system paths in a portable way.
using System.IO;

// Quick illustration of the classes we will use.
File.WriteAllText("hello.txt", "Hello World");
string content = File.ReadAllText("hello.txt");

Directory.CreateDirectory("data");
string[] files = Directory.GetFiles("data");

By the end of the section you will be comfortable creating, reading and modifying files from your C# programs. This is an essential skill: most real-world applications need to persist data, import settings, generate reports or read input from the disk. Let's get started.