C# Path GetDirectoryName() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

In C#, Path.GetDirectoryName() returns the folder part of a path: everything before the last separator. For "/data/reports/2026.txt" the answer is "/data/reports". It is a text answer, so the folder does not have to exist.

Two special answers matter. If the path is a root (such as "/"), the result is null. If the path has no folder part (such as "file.txt"), the result is an empty string. Windows also converts / to \ in the result, which is why the examples call Replace.

This is a static method of System.IO.Path. Call it as Path.GetDirectoryName(...); there is no new Path(). Like most Path methods, it only works with text: it never opens, reads, or creates a file, and it works the same whether or not the path exists.

Syntax

Pass a path. The result is a string, or null for a root.

C#
string dir = Path.GetDirectoryName("/data/reports/2026.txt");

Console.WriteLine(dir.Replace('\\', '/'));   // /data/reports
CallWhat it does
GetDirectoryName("/data/a.txt")Returns /data.
GetDirectoryName("/data/reports/")Returns /data/reports. A trailing separator makes the whole thing the folder part.
GetDirectoryName("file.txt")No folder part. Returns an empty string.
GetDirectoryName("/")A root has no parent. Returns null.
GetDirectoryName(null)Returns null.

The result has no trailing separator, except for a root-like answer such as "/". To go up two levels, call the method twice.

Library declarations
C#
public static string? GetDirectoryName(string? path);
public static ReadOnlySpan<char> GetDirectoryName(ReadOnlySpan<char> path);

Parameters

ParameterDescription
pathThe path to read. It can be a file path or a folder path, absolute or relative, and it does not need to exist.

Return Value

Return ValueDescription
string?The folder part. It is null if path is null or a root, and an empty string if there is no folder part. The span overload returns a span instead.

C# Examples

Example 1 — Climb From a File Up to the Root

Call GetDirectoryName again and again until it returns null.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string current = "/data/reports/2026.txt";

        while (current != null) {
            current = Path.GetDirectoryName(current);
            Console.WriteLine(current == null ? "(null)" : current.Replace('\\', '/'));
        }
    }
}

How It Works

  1. First step. The text before the last separator of the file path is /data/reports. Replace keeps the output the same if Windows answers with backslashes.
  2. Second step. The same call on /data/reports gives /data. Each answer is shorter, so the loop must end.
  3. The root. The parent of /data is /, the root. On Windows this prints a backslash that Replace turns into a slash.
  4. null ends the loop. A root has no parent, so the next call returns null. The loop condition current != null then stops it, and (null) is printed first.

Example 2 — null, Empty, and Trailing Separators

Three paths that look odd. Square brackets show the empty string clearly.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        Console.WriteLine("[" + Path.GetDirectoryName("file.txt") + "]");
        Console.WriteLine(Path.GetDirectoryName("/") == null);

        string missing = null;
        Console.WriteLine(Path.GetDirectoryName(missing) == null);

        Console.WriteLine(Path.GetDirectoryName("/data/reports/").Replace('\\', '/'));
        Console.WriteLine(Path.GetDirectoryName("/data/reports").Replace('\\', '/'));
    }
}

How It Works

  1. No folder part. "file.txt" has no separator, so the answer is an empty string. The brackets make the empty text visible.
  2. A root gives null. "/" has no parent, so the comparison with null is True.
  3. null in, null out. The variable missing is null, so the answer is null again. No exception is thrown.
  4. The trailing separator counts. With a slash at the end, the whole text before it is the folder part, so you get /data/reports. Without the slash, reports is the last part and the answer is /data.

Example 3 — Create the Parent Folder Before You Write

A common job: take the folder part of a file path, create that folder, then write the file. Everything happens in the temp folder.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-dirname-demo");
        if (Directory.Exists(root)) Directory.Delete(root, true);

        string file = Path.Combine(root, "out", "result.txt");
        string folder = Path.GetDirectoryName(file);

        Console.WriteLine("Folder name: " + Path.GetFileName(folder));
        Console.WriteLine("Folder exists: " + Directory.Exists(folder));

        Directory.CreateDirectory(folder);
        File.WriteAllText(file, "done");

        Console.WriteLine("Folder exists: " + Directory.Exists(folder));
        Console.WriteLine("File exists: " + File.Exists(file));

        Directory.Delete(root, true);
    }
}

How It Works

  1. A private demo folder. root sits inside GetTempPath, and any leftover from an earlier run is removed first. The file path adds an out folder that does not exist yet.
  2. Take the folder part. GetDirectoryName(file) is the path of out. GetFileName then trims it to the name out, so no machine-specific path is printed.
  3. Only text so far. Directory.Exists prints False, because building the path created nothing.
  4. Create, write, check. CreateDirectory makes the folder, so WriteAllText can succeed. The last two checks print True, and the final line deletes everything.

Frequently Asked Questions

Call Path.GetDirectoryName(path). For "/data/reports/2026.txt" it returns "/data/reports". Use Path.GetFileName if you need the last part instead.
It returns null when the path is null or a root such as "/" or, on Windows, "C:\". A root has no parent folder, so there is nothing to return. Test for null before you call another method on the result.
The path has no folder part, for example "file.txt". An empty string means "the current folder, written as nothing". Do not pass it to Directory.CreateDirectory.
Trim the trailing separator first, then call GetDirectoryName: Path.GetDirectoryName(Path.TrimEndingDirectorySeparator("/data/reports/")) is "/data". For a real folder, Directory.GetParent also works.
No. It only reads the text. The folder in the path can be missing, and the method still returns an answer. Use Directory.Exists when you need a real check.

Next: GetExtension()

Get the extension of a file name, including the leading dot.

GetExtension() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful