- `Path.Combine`
- `Path.GetDirectoryName`
- `Path.GetFileName`
- `Path.GetFullPath`
- `Path.GetExtension`
- `Path.GetFileNameWithoutExtension`
- `Path.HasExtension`
- `Path.ChangeExtension`
- `Path.GetPathRoot`
- `Path.IsPathRooted`
C#
中的
Path
是
System.IO
命名空间中的一个类,提供了用于操作文件路径的方法。以下是一些常用的
Path
类方法:
Path.Combine
用于组合多个路径部分,返回一个完整的路径字符串。
string path = Path.Combine("folder", "subfolder", "file.txt");
- 如果
path2
是绝对路径 path2
开头为\
或/
string path = Path.Combine(path1, path2);
// path == path2
Path.GetDirectoryName
返回指定路径的目录信息。
返回父文件夹
string directoryName = Path.GetDirectoryName("folder\\subfolder\\file.txt");
//folder\subfolderstring directoryName = Path.GetDirectoryName(@"D:\");
Console.WriteLine("!" + directoryName + "!");
//!!
Path.GetFileName
返回指定路径的文件名部分。
返回最下级文件(夹)名
string fileName = Path.GetFileName("folder\\subfolder\\file.txt");
//file.txtstring fileName = Path.GetFileName("folder\\subfolder");
//subfolderstring fileName = Path.GetFileName("folder\\subfolder\\");
Console.WriteLine("!" + fileName + "!");
//!!
Path.GetFullPath
返回指定路径的绝对路径。
- 指定路径为相对路径
工作路径+相对路径 - 指定路径为绝对路径
绝对路径
string fullPath = Path.GetFullPath("relative\\path");
Path.GetExtension
返回文件的扩展名。
string extension = Path.GetExtension(@"D:\123.txt");
Console.WriteLine("!" + extension + "!");
//!.txt!string extension = Path.GetExtension(@"D:\");
Console.WriteLine("!" + extension + "!");
//!!
Path.GetFileNameWithoutExtension
返回不包含扩展名的文件(夹)名。
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension("file.txt");
//filestring fileNameWithoutExtension =Path.GetFileNameWithoutExtension(@"D:\Computer\MATLAB");
//MATLAB
Path.HasExtension
检查路径是否包含扩展名。
bool hasExtension = Path.HasExtension("file.txt");
//Truebool hasExtension = Path.HasExtension("file");
//False
Path.ChangeExtension
更改文件(夹)的扩展名。
string newFileName = Path.ChangeExtension("file.txt", ".md");
//file.mdstring newFileName = Path.ChangeExtension("\file", ".md");
//\file.md
Path.GetPathRoot
获取路径的根。
string pathRoot = Path.GetPathRoot("C:\\folder\\file.txt");
//C:\string pathRoot = Path.GetPathRoot("\\folder\\file.txt");
//\string pathRoot = Path.GetPathRoot("file.txt");
Console.WriteLine("!" + pathRoot + "!");
//!!
Path.IsPathRooted
判断路径是否为根路径。
是否有根
bool isPathRooted = Path.IsPathRooted("C:\\folder\\file.txt");
//Truebool isPathRooted = Path.IsPathRooted("\\file.txt");
//Truebool isPathRooted = Path.IsPathRooted("file.txt");
//False
这些是 Path
类的一些基本用法,它们可以帮助你处理文件和目录路径,确保你的应用程序能够正确地处理文件系统路径。如果你需要更具体的帮助或示例,请提供更多的上下文或问题。