Search code examples
c#absolute-path

How can we remove certain folder name from the path and return new path?


I have a path:

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

I need to check if this path has folder "TestResults", if it has then I need to remove this and return new path as

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

I know I can achieve this using trim and split. But just to make sure I pick up a right choice. What is the best way of achieving this?

Any help really appriciated.


Solution

  • i would not use string replace method in this case. Why?

    e.g. :

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

    that is not what you expected.

    so how to fix this,

    path = string.Join(Path.DirectorySeparatorChar.ToString(),      
               path.Split(Path.DirectorySeparatorChar).Where(x=> x!="Users1").ToArray()));
    
    //C:\Users2\Users122\Users13\Users133\filename.xml