替换C# .NET 6中的相对路径反斜杠

huangapple go评论67阅读模式
英文:

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&#39;m trying to get a specific format of the output of the relative path between two paths like so:

```c#
var from = @&quot;C:\This\is\my\path\folder1&quot;;
var to = @&quot;C:\This\is\my\path\folder2\folder3&quot;;

var relativePath = System.IO.Path.GetRelativePath(from, to);

System.Console.WriteLine(relativePath);
// output --&gt; ..\folder2\folder3
// desired output --&gt; ../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 = $&quot;{relativePath.Replace(&#39;\\&#39;, &#39;/&#39;)}/&quot;;

System.Console.WriteLine(desiredOutput );
// output --&gt; ../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 = @&quot;C:\This\is\my\path\folder1&quot;;
  var to = @&quot;C:\This\is\my\path\folder2\folder3&quot;;

  var relativePath = Path.GetRelativePath(from, to);
  relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

  System.Console.WriteLine(relativePath);

huangapple
  • 本文由 发表于 2023年6月29日 19:28:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定