Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Path.Combine() / Path.GetFileName()

Path.Combine() / Path.GetFileName()

Path.Combine() safely joins file paths, and Path.GetFileName() extracts the filename portion from a path.

Syntax

// Joins paths together. Automatically inserts the OS path separator.
Path.Combine(string path1, string path2)
Path.Combine(params string[] paths)

// Gets the filename (including extension) from a path.
Path.GetFileName(string path)

// Gets the filename without the extension from a path.
Path.GetFileNameWithoutExtension(string path)

// Gets the extension from a path (includes the leading dot).
Path.GetExtension(string path)

// Gets the directory portion from a path.
Path.GetDirectoryName(string path)

Method List

MethodDescription
Path.Combine(path1, path2)Joins two or more paths. Automatically inserts the OS path separator (\ on Windows, / on Linux/Mac).
Path.GetFileName(path)Returns only the filename (including extension) from a path string.
Path.GetFileNameWithoutExtension(path)Returns the filename without the extension.
Path.GetExtension(path)Returns the extension (e.g., .txt). Returns an empty string if there is no extension.
Path.GetDirectoryName(path)Returns the directory portion of the path, excluding the filename.

Sample Code

using System;
using System.IO;

// Join paths using Path.Combine().
string folder = @"C:\Users\akiba\documents";
string fileName = "report.txt";
string fullPath = Path.Combine(folder, fileName);
Console.WriteLine(fullPath); // C:\Users\akiba\documents\report.txt

// You can also join three or more paths.
string savePath = Path.Combine(@"C:\data", "2024", "01", "log.csv");
Console.WriteLine(savePath); // C:\data\2024\01\log.csv

// Extract the filename using Path.GetFileName().
string path = @"C:\Users\akiba\documents\report.txt";
Console.WriteLine(Path.GetFileName(path));                    // report.txt
Console.WriteLine(Path.GetFileNameWithoutExtension(path));    // report
Console.WriteLine(Path.GetExtension(path));                   // .txt
Console.WriteLine(Path.GetDirectoryName(path));               // C:\Users\akiba\documents

Overview

Path.Combine() is a safer way to join paths than concatenating strings directly. It automatically handles duplicate or missing separators, so the same code works on Windows, Linux, and Mac.

Manually concatenating paths with strings (e.g., path1 + "\\" + path2) is error-prone due to OS differences and separator mistakes, so always use Path.Combine() instead.

For reading and writing files, see File.ReadAllText() / File.WriteAllText().

If you find any errors or copyright issues, please .