【问题标题】:How can we remove certain folder name from the path and return new path?我们如何从路径中删除某些文件夹名称并返回新路径?
【发布时间】:2013-08-24 11:35:43
【问题描述】:

我有一条路:

 "C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml"

我需要检查这个路径是否有文件夹“TestResults”,如果有,那么我需要删除它并返回新路径

"C:\\Users\\dev\\Test\\Config\\Report.xml"

我知道我可以使用修剪和拆分来实现这一点。但只是为了确保我选择了正确的选择。实现这一目标的最佳方法是什么?

非常感谢任何帮助。

【问题讨论】:

  • path.Replace("\\TestResults\\","") ?

标签: c# absolute-path


【解决方案1】:

在这种情况下,我不会使用字符串替换方法。为什么?

例如:

string path = "C:\\Users1\\Users2\\Users122\\Users13\\Users133\\filename.xml";
path = path.Replace("\\TestResults", string.Empty);
// you will get "C:\Users222333\filename.xml"

这不是你所期望的。

那么如何解决这个问题,

path = string.Join(Path.DirectorySeparatorChar.ToString(),      
           path.Split(Path.DirectorySeparatorChar).Where(x=> x!="Users1").ToArray()));

//C:\Users2\Users122\Users13\Users133\filename.xml

【讨论】:

    【解决方案2】:

    你可以使用String.Replace这样的方法;

    返回一个新字符串,其中所有出现的指定 Unicode 当前字符串中的字符或字符串被替换为另一个 指定的 Unicode 字符或字符串。

    string path = "C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml";
    path = path.Replace("\\TestResults", string.Empty);
    Console.WriteLine(path);
    

    输出将是;

    C:\Users\dev\Test\Config\Report.xml
    

    这里是DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多