Remove the extra slash "\" from the string path file in C #

How to convert

"String path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";

at

String path = @"C:\Abc\Omg\Why\Me\".

My approach is to first reverse stringand then delete everything "\" until we get the first one char , and reverseit again.

How to do this in C #, is there any method for such an operation?

+6
source share
4 answers

You can simply build the path using a static class Path:

string path = Path.GetFullPath(@"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");

After this operation, the variable Pathwill contain the minimum version:

C:\Abc\Omg\Why\Me\
+20
source

You can use path.TrimEnd('\\'). See the documentation for String.TrimEnd.

, .

+9
var path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';

var path = @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);
+3

You can also delete multiple slashes using a regular expression, as shown below:

 string path= @"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
 path = Regex.Replace(path, "\\\\{2,}", @"\");
0
source

Source: https://habr.com/ru/post/1663744/


All Articles