Reputation: 918
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.
Upvotes: 0
Views: 129
Reputation: 63065
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
Upvotes: 1
Reputation: 98750
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.
Upvotes: 1