您的位置:首页 > 编程语言 > C#

C# Path类常用操作

2015-08-06 08:55 495 查看

C#_Path类常用操作System.IO.Path

对一个路径做相应操作,包括文件路径,目录路径。通常会用到Path这个类。列举一些常用的操作。1.更改路径字符串的扩展名
public static string ChangeExtension(string path,string extension)
参数:path(String):要修改的路径信息.extension(String):新的扩展名。返回值:String,修改后的路径字符串。如果 extension 是 null,则返回的字符串包含指定的路径,其扩展名已移除(点还在)。
string s =Path.ChangeExtension(@"c:\path.dll", "");//返回:"c:\path."
如果 path 是 null 或空字符串 (""),则返回的路径信息是未修改的。
string s2 = Path.ChangeExtension("", ".txt");//返回:""
如果 path 不具有扩展名,并且 extension 不是 null,则返回的路径字符串包含 extension,它追加到 path 的结尾。
string s3 = Path.ChangeExtension(@"c:\目录", ".txt");//返回:"c:\目录.txt"。 如果这里的extension不含句点,会自动添加,返回的还是"c:\目录.txt"
仅更改路径字符串中的扩展名,并不会改变实际文件的扩展名或者目录。2. 合并两个字符路径字符串
public static string Combine(string path1,string path2)
参数:path1(String) ,第一个路径path2(String), 第二个路径返回值:String ,合并后的路径字符串。常见的合并操作为:
string path1 = @"c:\目录"; string path2 = @"install.txt"; string s4 = Path.Combine(path1, path2); //返回:"c:\目录\install.txt"
注意:
合并 'c:\temp' 和 'subdir\file.txt', 结果: 'c:\temp\subdir\file.txt' 合并 'c:\temp' 和 'c:\temp.txt', 结果: 'c:\temp.txt' 合并 'c:\temp.txt' 和 'subdir\file.txt', 结果: 'c:\temp.txt\subdir\file.txt' 合并 'c:^*&)(_=@#'\^.*(.txt' 和 'subdir\file.txt', 结果: 'c:^*&)(_=@#'\^.*(.txt\subdir\file.txt' 合并''(这里的path1为"") 和 'subdir\file.txt', 结果: 'subdir\file.txt' 不能合并 ''(这里的path1为null) 和 'subdir\file.txt' 因为:值不能为null,但可以为""
3.获取指定路径字符串的目录信息
public static string GetDirectoryName(string path)
直接看几个示例了:
string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string rootPath = @"C:\"; Path.GetDirectoryName(fileName); //返回:'C:\mydir' Path.GetDirectoryName(path); //返回:'C:\mydir' Path.GetDirectoryName(rootPath); //返回:''
4.获取指定路径字符串的扩展名
public static string GetExtension(string path)
string fileName = @"C:\mydir.old\myfile.ext"; string path = @"C:\mydir.old\"; string extension; Path.GetExtension(fileName); //返回 : '.ext' Path.GetExtension(path); //返回 :''
5.获取文件名称
string strFrom = Path.GetFileName(openFileDialog1.FileNames[k]);

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: