简体   繁体   English

从c#中的字符串文件路径中删除额外的反斜杠“\\”

[英]Remove Extra back slash “\” from string file path in c#

How to convert 如何转换

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

into

String path = @"C:\\Abc\\Omg\\Why\\Me\\" . 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. 我的方法是首先reverse string ,然后删除所有 "\\"直到我们得到第一个 char ,然后再reverse

How to do this in C#, is there any method for such operation? 如何在C#中执行此操作,是否有任何此类操作的方法?

You can just construct path using the Path static class: 您可以使用Path静态类构造路径:

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

After this operation, variable path will contain the minimal version: 执行此操作后,变量path将包含最小版本:

C:\Abc\Omg\Why\Me\

You can use path.TrimEnd('\\\\') . 您可以使用path.TrimEnd('\\\\') Have a look at the documentation for String.TrimEnd . 看看String.TrimEnd的文档。

If you want the trailing slash, you can add it back easily. 如果你想要尾部斜杠,你可以轻松地添加它。

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

another solution is 另一种解决方案是

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

You can also remove multiple slash using Regular expression as follow: 您还可以使用正则表达式删除多个斜杠,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM