C# 截取带路径的文件名字,扩展名,等等 的几种方法

112 阅读1分钟

C#对磁盘IO操作的时候,经常会用到这些,路径,文件,文件名字,文件扩展名.

string filePath = "E:\Randy0528\中文目录\JustTest.rar";
//文件路径


Response.Write("<br/>更改路径字符串的扩展名。<br/>");
Response.Write(System.IO.Path.ChangeExtension(filePath, "txt")); 
//结果  E:\Randy0528\中文目录\JustTest.txt


Response.Write("<br/>返回指定路径字符串的目录信息。。<br/>");
Response.Write(System.IO.Path.GetDirectoryName(filePath));  
//结果  E:\Randy0528\中文目录


Response.Write("<br/>返回指定的路径字符串的扩展名。<br/>");
Response.Write(System.IO.Path.GetExtension(filePath));
//结果  .rar


Response.Write("<br/>返回指定路径字符串的文件名和扩展名。<br/>");
Response.Write(System.IO.Path.GetFileName(filePath));  
//结果  JustTest.rar


Response.Write("<br/>返回不具有扩展名的指定路径字符串的文件名。<br/>");
Response.Write(System.IO.Path.GetFileNameWithoutExtension(filePath));
//结果  JustTest


Response.Write("<br/>获取指定路径的根目录信息。<br/>");
Response.Write(System.IO.Path.GetPathRoot(filePath));
//结果  E:\


Response.Write("<br/>返回随机文件夹名或文件名。<br/>");
Response.Write(System.IO.Path.GetRandomFileName());   
//结果   ct2h5b2h.sed


Response.Write("<br/>创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径。<br/>");
Response.Write(System.IO.Path.GetTempFileName());   
//结果 C:\Documents and Settings\Randy\Local Settings\Temp\tmpAD.tmp


Response.Write("<br/>返回当前系统的临时文件夹的路径。<br/>");
Response.Write(System.IO.Path.GetTempPath());      
//结果 C:\Documents and Settings\Randy\Local Settings\Temp\    


Response.Write("<br/>确定路径是否包括文件扩展名。<br/>");
Response.Write(System.IO.Path.HasExtension(filePath)); //结果:True


Response.Write("<br/>获取一个值,该值指示指定的路径字符串是包含绝对路径信息还是包含相对路径信息。<br/>");
Response.Write(System.IO.Path.IsPathRooted(filePath)); //结果:True