此类用于处理文件路径
using System; using System.IO; namespace PathTest { class Program { static void Main(string[] args) { string s; Console.WriteLine("Path类的使用"); string path1 = @"D:\path1"; string path2 = @"path2"; string file = @"test.txt"; string filePath = @"D:\path\test.txt"; Console.WriteLine("path1={0}", path1); Console.WriteLine("path2={0}", path2); Console.WriteLine("file={0}", file); Console.WriteLine("filePath={0}", filePath); Console.WriteLine(); //更改扩展名 s = Path.ChangeExtension(filePath, "bin"); Console.WriteLine("ChangeExtension={0}", s); //合并路径 s = Path.Combine(path1, path2); Console.WriteLine("Combine={0}", s); //获取目录名 s = Path.GetDirectoryName(filePath); Console.WriteLine("GetDirectoryName={0}", s); //获取扩展名 s = Path.GetExtension(filePath); Console.WriteLine("GetExtension={0}", s); //获取文件名 s = Path.GetFileName(filePath); Console.WriteLine("GetFileName={0}", s); //获取不带扩展名的文件名 s = Path.GetFileNameWithoutExtension(filePath); Console.WriteLine("GetFileNameWithoutExtension={0}", s); //获取路径的完全限定名 s = Path.GetFullPath(path2); Console.WriteLine("GetFullPath={0}", s); //获取根目录 s = Path.GetPathRoot(filePath); Console.WriteLine("GetPathRoot={0}", s); //返回随机文件名 s = Path.GetRandomFileName(); Console.WriteLine("GetRandomFileName={0}", s); //随机创建临时文件名 s = Path.GetTempFileName(); Console.WriteLine("GetTempFileName={0}", s); //返回当前系统临时文件夹路径 s = Path.GetTempPath(); Console.WriteLine("GetTempPath={0}", s); //路径是否包含文件扩展名 bool b = Path.HasExtension(filePath); Console.WriteLine("HasExtension={0}", b); //判断是否为绝对路径 b = Path.IsPathRooted(filePath); Console.WriteLine("IsPathRooted={0}", b); //获取不允许在文件名中使用的字符数组 char[] chars = Path.GetInvalidFileNameChars(); //获取不允许在路径中使用的字符数组 chars = Path.GetInvalidPathChars(); Console.Read(); } } }
运行效果