Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Extra back slash "\" from string file path in c#

Tags:

string

c#

.net

How to convert

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

into

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

My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.

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

like image 358
Pranay Deep Avatar asked Dec 14 '16 11:12

Pranay Deep


People also ask

Why is there a double slash in path?

Double Backslashes (\\)Two backslashes are used as a prefix to a server name (hostname). For example, \\a5\c\expenses is the path to the EXPENSES folder on the C: drive on server A5. See UNC, \\, path and forward slash.

How to remove extra slash from path in c#?

TrimEnd(new[] { '/' }); With this method you can also specify multiple characters so you may want to remove all slash or backslash using the array. 1string fileName = "Test\\\\"; fileName= fileName. TrimEnd(new[] { '/', '\\\\' });

How to remove backward slash from String in c#?

Replace(@"\\",@""); String abc = result. Replace(@"\\",string. Empty);

How do you get rid of the backslash in a text file in Python?

Using strip() Function to Remove Backslash from String in Python.


2 Answers

You can just construct path using the Path static class:

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

After this operation, variable path will contain the minimal version:

C:\Abc\Omg\Why\Me\
like image 77
Zoran Horvat Avatar answered Sep 20 '22 01:09

Zoran Horvat


You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.

If you want the trailing slash, you can add it back easily.

like image 29
Daniel A. White Avatar answered Sep 18 '22 01:09

Daniel A. White