文件操作是一项普通的编程任务,但是在操作各式各样的路径属性时,它很快就会变得让人生厌。例如,你可能需要确定与一个路径或者特定的文件相关联的扩展名。进行这样一项任务常常需要各种字符串函数,但是.NET框架包括了Path类,它会简化这些任务。
Path类放在System.IO命名空间里。Path是一个只包含有静态方法的实例类,所以它不需要在使用之前实例化。它有各种方法用于处理文件的扩展名、文件名、根路径,以及和更多和路径相关的方面。下面就是可用方法的一个简表:
这些方法把主控权交到你的手里。他们会简化操作文件名及其路径各个方面的任务。使用示例代码能够更好地说明这些方法。下面的C#列表简要地说明了Path类的强大能力:
using System.IO;
string pth = "c:buildertesttest.txt";
if (Path.HasExtension(pth)) {
Console.WriteLine("Path has an extension: .", Path.GetExtension(pth));
} else {
Console.WriteLine("Path has no extension: .",
Path.GetFileNameWithoutExtension(pth));
}
if (Path.IsPathRooted(pth)) {
Console.WriteLine("The path contains root information: .",
Path.GetPathRoot(pth));
}
Console.WriteLine("The filename is .", Path.GetFileName(pth));
Console.WriteLine("The full path is .", Path.GetFullPath(pth));
Console.WriteLine("The location for temporary files is .",
Path.GetTempPath());
Console.WriteLine("The following temp file is available: .",
Path.GetTempFileName());
Console.WriteLine("The set of invalid characters in a path is:");
foreach (char c in Path.InvalidPathChars) {
Console.WriteLine(c);
}