Question

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.

Was it helpful?

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

OTHER TIPS

You can use String.Replace method like;

Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.

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

Output will be;

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

Here a DEMO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top