[C#] Safely Joining File Paths Without Worrying About Separators (Path.Combine)

When building file or directory paths in a program, using simple string concatenation (like the + operator) is dangerous. This is because path separators differ by OS (Windows uses \, Linux/Mac uses /), and mistakes often occur regarding whether a separator already exists at the end of a string.

Using the System.IO.Path.Combine method automatically handles these differences and joins paths in the correct format for the execution environment.

目次

Table of Contents

  • Implementation Example: Creating a Settings File Path
  • Sample Code
  • Execution Result (Windows Example)
  • Explanation and Technical Points
    1. Benefits of Path.Combine
    2. Multiple Arguments
    3. Behavior with Absolute Paths (Note)

Implementation Example: Creating a Settings File Path

In the following sample code, I create a full path by combining the user’s application data folder (AppData), an app-specific folder, and a settings filename.

Sample Code

C#

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // Path components to combine
        // 1. System ApplicationData folder (e.g., C:\Users\User\AppData\Roaming)
        string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        
        // 2. Application name
        string appName = "MyTextEditor";
        
        // 3. File name
        string fileName = "settings.xml";

        Console.WriteLine($"[1] Base: {baseDir}");
        Console.WriteLine($"[2] App : {appName}");
        Console.WriteLine($"[3] File: {fileName}");
        Console.WriteLine();

        // ---------------------------------------------------------
        // Safely combine using Path.Combine
        // You can pass 3 or more arguments, not just 2
        // ---------------------------------------------------------
        string fullPath = Path.Combine(baseDir, appName, fileName);

        Console.WriteLine("--- Combined Result ---");
        Console.WriteLine(fullPath);
    }
}

Execution Result (Windows Example)

Plaintext

[1] Base: C:\Users\YourName\AppData\Roaming
[2] App : MyTextEditor
[3] File: settings.xml

--- Combined Result ---
C:\Users\YourName\AppData\Roaming\MyTextEditor\settings.xml

Explanation and Technical Points

1. Benefits of Path.Combine

Compared to string concatenation (e.g., baseDir + "\\" + appName), this method offers the following benefits:

  • Automatic Separator Handling: It properly joins paths regardless of whether the previous path ends with a separator (preventing double slashes \\ or missing slashes).
  • Cross-Platform: It automatically selects \ for Windows and / for Linux/macOS.

2. Multiple Arguments

Path.Combine can accept not just two, but three, four, or more path parts in succession. Passing an array is also possible.

C#

string[] parts = { "C:", "Windows", "System32", "drivers", "etc", "hosts" };
string path = Path.Combine(parts);

3. Behavior with Absolute Paths (Note)

If an “absolute path” (e.g., C:\Logs or /var/log) is included in the middle of the arguments, Path.Combine ignores all preceding paths and returns the result starting from that absolute path.

C#

// "logs" is ignored, and "C:\temp\file.txt" is returned
Path.Combine("logs", @"C:\temp", "file.txt");
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次