英文:
Replace relative path backslashes in C# .NET 6
问题
I'm here to help with the translation. Here's the translated part:
我正在尝试获取两个路径之间的相对路径的特定格式,如下所示:
```c#
var from = @"C:\This\is\my\path\folder1";
var to = @"C:\This\is\my\path\folder2\folder3";
var relativePath = System.IO.Path.GetRelativePath(from, to);
System.Console.WriteLine(relativePath);
// output --> ..\folder2\folder3
// desired output --> ../folder2/folder3/
非常重要的是,末尾需要包含 /
,因为最终我需要将输出作为另一个字符串的替代字符串。
是否有其他方法可以获得所需的输出,而无需操作字符串,比如使用框架函数或其他方法?
var desiredOutput = $"{relativePath.Replace('\\', '/')}/";
System.Console.WriteLine(desiredOutput );
// output --> ../folder2/folder3/
希望这有所帮助。如果有其他问题,请随时提出。
<details>
<summary>英文:</summary>
I'm trying to get a specific format of the output of the relative path between two paths like so:
```c#
var from = @"C:\This\is\my\path\folder1";
var to = @"C:\This\is\my\path\folder2\folder3";
var relativePath = System.IO.Path.GetRelativePath(from, to);
System.Console.WriteLine(relativePath);
// output --> ..\folder2\folder3
// desired output --> ../folder2/folder3/
It's important that there is also the trailing /
because in the end i need the output as a subtitution string for another string.
Is there another way to get the desired output without manipulating the string, like a framework function or something?
Or is this the only solution?
var desiredOutput = $"{relativePath.Replace('\\', '/')}/";
System.Console.WriteLine(desiredOutput );
// output --> ../folder2/folder3/
答案1
得分: 2
以下是翻译好的内容:
似乎可以替换DirectorySeperatorChar。
更健壮的做法是使用System.IO已经提供的功能。
var from = @"C:\This\is\my\path\folder1";
var to = @"C:\This\is\my\path\folder2\folder3";
var relativePath = Path.GetRelativePath(from, to);
relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
System.Console.WriteLine(relativePath);
英文:
Seems fine to replace the DirectorySeperatorChar.
A litte bit more robust would be the usage of what System.IO already offers.
var from = @"C:\This\is\my\path\folder1";
var to = @"C:\This\is\my\path\folder2\folder3";
var relativePath = Path.GetRelativePath(from, to);
relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
System.Console.WriteLine(relativePath);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论