zoukankan      html  css  js  c++  java
  • [转载]C#_Path类常用操作

    C#_Path类常用操作

    感谢李佳龙专栏http://www.cnblogs.com/lijialong/archive/2010/07/05/path.html

    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:^*&)(_=@#'\^&#2.*(.txt' 和 'subdir\file.txt', 结果: 
    'c:^*&)(_=@#'\^&#2.*(.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);
    //返回 :''
  • 相关阅读:
    ZOJ 1060 Count the Color
    POJ 3321 Apple Tree
    数字三角形模型
    静态维护区间加等差数列的求和问题
    Codeforces Round #622 (Div. 2)-题解
    算法竞赛进阶指南0x00-算法基础
    Codeforces Round #628 (Div. 2)
    Codeforces Round #625 (Div. 2, based on Technocup 2020 Final Round)
    Codeforces Round #621 (Div. 1 + Div. 2)
    Codeforces Round #620 (Div. 2) 题解
  • 原文地址:https://www.cnblogs.com/xhiyu/p/1970698.html
Copyright © 2011-2022 走看看