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:
Syntax
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
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));
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Concatenating paths with
+and getting wrong separators; usePath.Combine. - Assuming
Path.Combinevalidates that the path exists. - 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: