ZetCode

C# 路径

最后修改于 2025 年 4 月 20 日

本教程介绍了如何在 C# 中使用 Path 类来操作文件和目录路径。Path 类提供了用于常见路径操作的方法。

Path 类是一个静态类,包含用于对表示文件或目录路径的字符串执行操作的方法。 它以跨平台的方式处理路径操作。

PathSystem.IO 命名空间的一部分,并且可以处理绝对路径和相对路径。 它自动处理特定于平台的路径分隔符和验证规则。

基本路径操作

此示例演示了基本路径操作,包括组合路径和获取文件扩展名。 这些是在使用文件系统时常见的任务。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string dir = @"C:\Users\Public\Documents";
        string file = "report.txt";
        
        // Combine paths
        string fullPath = Path.Combine(dir, file);
        Console.WriteLine($"Combined path: {fullPath}");
        
        // Get file extension
        string ext = Path.GetExtension(fullPath);
        Console.WriteLine($"File extension: {ext}");
        
        // Get file name
        string fileName = Path.GetFileName(fullPath);
        Console.WriteLine($"File name: {fileName}");
        
        // Get directory name
        string dirName = Path.GetDirectoryName(fullPath);
        Console.WriteLine($"Directory: {dirName}");
    }
}

Path.Combine 方法使用当前平台的正确分隔符安全地组合路径段。 GetExtensionGetFileNameGetDirectoryName 提取路径组件。

此示例演示了如何在不硬编码分隔符的情况下处理路径。 这些方法会自动处理 Windows 反斜杠或 Unix 正斜杠。 输出演示了可靠地提取路径字符串的不同部分。

使用临时文件

Path 类提供了用于处理临时文件的方法。 此示例演示了如何以跨平台的方式创建和使用临时文件路径。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Get temp path
        string tempPath = Path.GetTempPath();
        Console.WriteLine($"Temp directory: {tempPath}");
        
        // Create temp file name
        string tempFile = Path.GetTempFileName();
        Console.WriteLine($"Temp file: {tempFile}");
        
        // Create random file name
        string randomName = Path.GetRandomFileName();
        Console.WriteLine($"Random name: {randomName}");
        
        // Clean up
        File.Delete(tempFile);
    }
}

GetTempPath 返回系统的临时目录。 GetTempFileName 创建一个唯一的临时文件并返回其路径。 GetRandomFileName 生成一个随机名称,但不创建文件。

该示例演示了正确的临时文件处理。 请注意,GetTempFileName 实际上会创建一个零字节文件,我们在最后将其删除。 当您只需要一个唯一名称时,GetRandomFileName 更安全。

路径验证和信息

此示例演示了如何使用 Path 类方法验证路径并获取路径信息。 这些对于可靠的文件操作至关重要。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Users\Public\Documents\data.json";
        
        // Check path properties
        Console.WriteLine($"Has extension: {Path.HasExtension(path)}");
        Console.WriteLine($"Is rooted: {Path.IsPathRooted(path)}");
        
        // Get path information
        Console.WriteLine($"Root: {Path.GetPathRoot(path)}");
        Console.WriteLine($"Full path: {Path.GetFullPath(path)}");
        
        // Invalid path characters
        Console.WriteLine("Invalid path chars:");
        foreach (char c in Path.GetInvalidPathChars())
        {
            Console.Write(c + " ");
        }
    }
}

HasExtension 检查路径是否具有文件扩展名。 IsPathRooted 确定路径是绝对路径还是相对路径。 GetPathRoot 提取路径的根部分。

该示例还演示了如何获取当前平台的无效路径字符。 这对于验证将用于文件路径的用户输入很有用。 这些方法有助于确保路径在用于文件操作之前有效。

更改文件扩展名

此示例演示了如何使用 Path 方法更改文件扩展名。 这是处理文件时常见的需求。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string originalFile = @"C:\data\report.txt";
        
        // Change extension
        string csvFile = Path.ChangeExtension(originalFile, ".csv");
        Console.WriteLine($"CSV file: {csvFile}");
        
        // Remove extension
        string noExt = Path.ChangeExtension(originalFile, null);
        Console.WriteLine($"No extension: {noExt}");
        
        // Multiple extensions
        string backupFile = Path.ChangeExtension(originalFile, ".bak.txt");
        Console.WriteLine($"Backup file: {backupFile}");
    }
}

ChangeExtension 修改路径字符串的扩展名。 传递 null 会完全删除扩展名。 该方法可以正确处理所有边缘情况。

该示例显示了不同的场景:更改为不同的扩展名、删除扩展名以及处理多个扩展名。 该方法不验证文件是否存在 - 它仅操作字符串表示形式。

相对路径和绝对路径

此示例演示了如何使用 Path 方法处理相对路径和绝对路径。 在这些路径类型之间进行转换在文件操作中很常见。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string basePath = @"C:\projects\app";
        string relativePath = @"src\utils\helper.cs";
        
        // Combine to full path
        string fullPath = Path.Combine(basePath, relativePath);
        Console.WriteLine($"Full path: {fullPath}");
        
        // Get relative path
        string otherFile = @"C:\projects\app\src\models\user.cs";
        string relativeToBase = Path.GetRelativePath(basePath, otherFile);
        Console.WriteLine($"Relative path: {relativeToBase}");
        
        // Get full path from relative
        string resolvedPath = Path.GetFullPath(relativePath, basePath);
        Console.WriteLine($"Resolved path: {resolvedPath}");
    }
}

GetRelativePath 计算从一个位置到另一个位置的相对路径。 GetFullPath 根据基本路径解析相对路径。 这些方法有助于在不同的路径表示形式之间导航。

该示例演示了如何在绝对路径和相对路径之间进行转换。 当您需要向用户显示路径或将路径存储在配置文件中时,这尤其有用。 这些方法会自动处理所有特定于平台的详细信息。

路径字符串操作

此示例显示了 Path 类提供的各种字符串操作方法。 当您需要使用路径组件时,这些方法很有用。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string longPath = @"C:\Users\Public\Documents\Projects\CSharp\App.cs";
        
        // Get parts of path
        Console.WriteLine($"File name without extension: {Path.GetFileNameWithoutExtension(longPath)}");
        Console.WriteLine($"Path separators: {Path.DirectorySeparatorChar}, {Path.AltDirectorySeparatorChar}");
        Console.WriteLine($"Volume separator: {Path.VolumeSeparatorChar}");
        
        // Join multiple parts
        string[] parts = { "C:", "data", "reports", "annual.pdf" };
        string joinedPath = Path.Join(parts);
        Console.WriteLine($"Joined path: {joinedPath}");
        
        // Trim trailing separators
        string messyPath = @"C:\temp\logs\\";
        string cleanPath = Path.TrimEndingDirectorySeparator(messyPath);
        Console.WriteLine($"Cleaned path: {cleanPath}");
    }
}

GetFileNameWithoutExtension 仅返回文件名部分,不带扩展名。 分隔符常量有助于编写跨平台代码。 Path.JoinCombine 的现代替代方案。

该示例演示了用于路径字符串操作的各种实用程序方法。 TrimEndingDirectorySeparator 对于清理用户提供的路径特别有用。 这些方法有助于确保在不同的平台和用例中保持一致的路径处理。

高级路径操作

此示例演示了更高级的路径操作,包括使用长路径和特殊文件夹。 这些技术对于复杂的场景很有用。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Special folders
        string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        Console.WriteLine($"Desktop path: {desktop}");
        
        // Long path handling
        string longPath = Path.Combine(desktop, "a".PadRight(200, 'a'), "test.txt");
        Console.WriteLine($"Long path length: {longPath.Length}");
        
        try
        {
            // Try to create long path
            Directory.CreateDirectory(Path.GetDirectoryName(longPath));
            File.WriteAllText(longPath, "Test content");
            Console.WriteLine("Long path created successfully");
            
            // Clean up
            File.Delete(longPath);
            Directory.Delete(Path.GetDirectoryName(longPath));
        }
        catch (PathTooLongException ex)
        {
            Console.WriteLine($"Path too long: {ex.Message}");
        }
        
        // Path comparison
        string path1 = @"C:\temp\file.txt";
        string path2 = @"C:\TEMP\FILE.TXT";
        bool equal = string.Equals(
            Path.GetFullPath(path1),
            Path.GetFullPath(path2),
            StringComparison.OrdinalIgnoreCase);
        Console.WriteLine($"Paths equal (case-insensitive): {equal}");
    }
}

该示例演示了如何访问特殊的系统文件夹并处理可能超出系统限制的长路径。 它还演示了不区分大小写的路径比较。

请注意,长路径支持取决于 Windows 版本和应用程序配置。 该示例包括针对路径相关异常的正确错误处理。 路径比较技术对于跨平台兼容性非常重要。

来源

Path 类文档

本教程介绍了如何使用 Path 类在 C# 中处理文件和目录路径,包括基本操作、临时文件、验证和高级技术。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 到目前为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程