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

Path

The Path class helps you build and take apart file addresses correctly, like a mapmaker who writes directions properly. It works with the text of the address without touching the file.

In this page:

  1. Path
Syntax
csharp
string full = Path.Combine(segment1, segment2, "file.txt");
Path.GetFileName(full);
Path.GetExtension(full);
Path.GetDirectoryName(full);

Path

The Path class manipulates file path strings without touching the filesystem — combining segments, extracting file names, and getting extensions.

Path.Combine builds a correct path for the current operating system, avoiding manual slash handling. Using Path methods instead of string concatenation avoids cross-platform path bugs.

Note: Always use Path.Combine instead of manually concatenating folder names with / or \\.

Example: Path

markup
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string fullPath = Path.Combine("data", "reports", "summary.txt");

        Console.WriteLine(fullPath);
        Console.WriteLine(Path.GetFileName(fullPath));
        Console.WriteLine(Path.GetExtension(fullPath));
        Console.WriteLine(Path.GetFileNameWithoutExtension(fullPath));
    }
}
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. Concatenating paths with + and getting wrong separators; use Path.Combine.
  2. Assuming Path.Combine validates that the path exists.
  3. Passing an absolute second path to Path.Combine, which discards the first part.
🔒

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.