C# Path

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

Definition and Usage

In C#, Path is a static class in the System.IO namespace. A path is the text that names a file or folder, such as reports/2026/summary.txt. The class gives you ready-made methods to join paths with Combine(), read the file name with GetFileName(), read the extension with GetExtension(), and make a full path with GetFullPath().

Because it is static, you never write new Path(). You call Path.Method(...). Add using System.IO; at the top of your file to use it. Almost every Path method is a string operation: it never opens a file and never checks that the path exists. The few exceptions are Exists(), GetTempFileName(), GetTempPath(), and the working-directory lookup inside GetFullPath().

The Path Methods index lists every method guide in this series.

Why not just use strings?

Paths look like simple text, but the rules differ by system and have many corner cases (double separators, dots in folder names, drive letters). Letting Path do the work removes a whole class of small bugs.

C# Syntax

Common first steps:

C#
using System.IO;

string file = Path.Combine("data", "notes.txt");      // join with the right separator

string name = Path.GetFileName(file);                  // notes.txt
string ext = Path.GetExtension(file);                  // .txt
string stem = Path.GetFileNameWithoutExtension(file);  // notes
string full = Path.GetFullPath(file);                  // adds the working directory
string temp = Path.GetTempPath();                      // the temp folder

Path vs File vs Directory

Three static classes in System.IO work with paths. Pick the one that matches the job:

ClassWhat it works withGood for
PathText only. It never touches the disk.Joining, splitting, and reading parts of a path; temp and random names
FileReal files on the disk.Read, write, copy, move, and delete a file. See C# File
DirectoryReal folders on the disk.Create, list, and delete a folder. See C# Directory

Windows vs Linux Paths

The same idea is written differently on each system. Path hides the difference, but you should know it exists:

ItemWindowsLinux and macOS
Folder separator\ (and / is also accepted)/ only
Root of a pathA drive such as C:\, or a network share/
Is /data/x.txt fully qualified?No (it uses the current drive)Yes
Is a backslash a separator?YesNo, it is an ordinary character in a name
Invalid file-name charactersAbout 41, including ? * : < > |Only / and the null character

Tip: write forward slashes in your input (Windows accepts them) and print results through Replace('\\', '/') when you need the same text on every system.

Which Method Should I Use?

Start from what you want to do:

I want to...UseRemember
Join folders and a file nameCombine(), Join()Combine drops earlier pieces after a rooted one; Join does not
Get the file name or extensionGetFileName(), GetExtension()The extension includes the dot
Get the folder of a fileGetDirectoryName()Returns an empty string or null in special cases
Check that something is on diskExists()True for a file or a folder; never throws
Make a full path from a short oneGetFullPath()Starts from the working directory
Find the path from one place to anotherGetRelativePath()Gives .. steps when needed
Get a temp file or a random nameGetTempFileName(), GetRandomFileName()Only the first one creates a file

C# Examples

Example 1 — Combine a Path, Then Read Its Parts

A first program with no files at all: build one path with Combine, then ask Path for each part of it.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string file = Path.Combine("reports", "2026", "summary.txt").Replace('\\', '/');

        Console.WriteLine(file);
        Console.WriteLine(Path.GetFileName(file));
        Console.WriteLine(Path.GetFileNameWithoutExtension(file));
        Console.WriteLine(Path.GetExtension(file));
        Console.WriteLine(Path.GetDirectoryName(file).Replace('\\', '/'));
    }
}

How It Works

  1. Build with Combine. Combine glues three pieces with the separator of your system. Windows would give reports\2026\summary.txt, so Replace('\\', '/') turns every backslash into a slash and the output is the same everywhere.
  2. Last part. GetFileName returns summary.txt, everything after the final separator. GetFileNameWithoutExtension drops the dot and what follows it, which leaves summary.
  3. The extension keeps its dot. GetExtension returns .txt, with the leading dot included.
  4. The folder part. GetDirectoryName returns everything before the final separator. Windows may answer with a backslash, so it gets the same Replace before printing.

Example 2 — A Path Is Only Text Until You Create the File

Build a path inside the temp folder, show that nothing exists there yet, then create the file and ask again.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string file = Path.Combine(Path.GetTempPath(), "codetofun-path-hub.txt");
        if (File.Exists(file)) File.Delete(file);

        Console.WriteLine(Path.GetFileName(file));
        Console.WriteLine(Path.GetExtension(file));
        Console.WriteLine("File exists: " + File.Exists(file));

        File.WriteAllText(file, "hello");
        Console.WriteLine("File exists: " + File.Exists(file));
        Console.WriteLine("Same name: " + (Path.GetFileName(file) == "codetofun-path-hub.txt"));

        File.Delete(file);
    }
}

How It Works

  1. A private demo path. GetTempPath plus a fixed file name gives a path that belongs to this lesson. The first if removes a leftover from an earlier run.
  2. Path works on text. GetFileName and GetExtension answer at once, even though the file has not been created.
  3. The disk says no. File.Exists prints False. This proves that a Path method never touches the disk. File and Directory are the classes that do.
  4. Create it, nothing else changes. After WriteAllText, File.Exists is True, and the path text and its file name are exactly the same as before. Then Delete cleans up.

Example 3 — Why Combine Beats the Plus Sign

Join two names with + and with Combine, and look at the separator characters of the current system.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string folder = "reports";
        string name = "summary.txt";

        Console.WriteLine("Plus sign: " + folder + name);
        Console.WriteLine("Combine: " + Path.Combine(folder, name).Replace('\\', '/'));
        Console.WriteLine("Trailing slash: " + Path.Combine("reports/", name));

        bool known = Path.DirectorySeparatorChar == '\\' || Path.DirectorySeparatorChar == '/';
        Console.WriteLine("Separator is slash or backslash: " + known);
        Console.WriteLine("Alt separator is slash: " + (Path.AltDirectorySeparatorChar == '/'));
    }
}

How It Works

  1. Plus forgets the separator. folder + name is plain text joining, so you get reportssummary.txt. You would have to remember a slash, and the right slash differs by system.
  2. Combine adds it for you. It puts Path.DirectorySeparatorChar between the pieces: a backslash on Windows, a slash on Linux and macOS. Replace then makes the printed text the same on every system.
  3. No double separators. "reports/" already ends with a separator, so Combine adds nothing and the result has a single slash. A forward slash counts as a separator on every system.
  4. Read the separators. DirectorySeparatorChar is \ on Windows and / on Linux and macOS, so the test is True on all of them. AltDirectorySeparatorChar is / on Windows and Linux, so that test is also True.

Next: C# Path Methods Index

After you know what the Path class is for, open the method index for a full tutorial on each Path API.

Start withWhy
Combine()Join paths safely, and learn the rooted-piece trap
GetFileName()Take the last part of a path
GetExtension()Read the extension, including the dot
GetFullPath()Turn a short path into a full one

Full list: C# Path Methods index (/c-sharp/path/method).

Frequently Asked Questions

Path is a static class in System.IO. It has methods to join paths, take them apart into folder, file name, extension and root, check them, and make full or relative paths. It works on strings and does not open any file.
Path works only with path text and never touches the disk. File reads, writes, copies, and deletes real files. Directory creates, lists, and deletes real folders. A normal program uses Path to build the text, then passes it to File or Directory.
It is the character this system puts between folders: a backslash on Windows, a forward slash on Linux and macOS. Path.AltDirectorySeparatorChar is the other accepted separator, a forward slash on Windows.
Combine adds the correct separator only when it is needed, never doubles one, and works the same on every operating system. The plus sign can give reportssummary.txt or reports//summary.txt, and hard-codes one kind of slash.
Open the C# Path Methods index. It lists Combine, Join, GetFileName, GetExtension, GetFullPath, GetRelativePath, the temp and random methods, and the invalid-character methods.

Browse every Path method

Open the methods index for categorized guides with examples and FAQs.

Path Methods Index →

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.

8 people found this page helpful