← Back to C# Course | Chapter 14: File I/O & Streams | Lesson 3 of 6

Directory

The Directory class deals with folders: making them, checking they exist, and listing what is inside. It is like a caretaker for your filing cabinets.

In this page:

  1. Directory
Syntax
csharp
Directory.CreateDirectory(path);
Directory.Exists(path);
string[] files = Directory.GetFiles(path);
Directory.Delete(path);

Directory

The Directory class provides static methods for creating, checking, listing, and deleting folders, such as Directory.CreateDirectory and Directory.Exists.

Directory.GetFiles returns the files inside a folder as an array of paths. It's the folder-level counterpart to the file-level File class.

Note: Directory.CreateDirectory does nothing (and doesn't throw) if the directory already exists.

Example: Directory

markup
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string folder = "reports";
        Directory.CreateDirectory(folder);

        Console.WriteLine(Directory.Exists(folder));

        File.WriteAllText(Path.Combine(folder, "a.txt"), "data");
        string[] files = Directory.GetFiles(folder);

        foreach (string f in files)
        {
            Console.WriteLine(f);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling Directory.Delete(path) on a folder that still has files, which throws an IOException; pass true as the second argument to delete its contents too.
  2. Calling Directory.GetFiles on a folder that does not exist, which throws a DirectoryNotFoundException; check Directory.Exists first.
  3. Assuming a relative path like "reports" is next to the source file, when it is relative to the program's current working directory.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.