硬编码 Windows 路径并转义反斜杠

Hardcoding a Windows path and escaping the backslashes

我正在尝试使用 Path.Combine 在 C# 中创建路径。

string documentPath = "C:\myApps\Application1\Documents\Project\"
string projectName = "Project1"
string combinedPath = System.IO.Path.Combine(documentPath, projectName)

最终组合路径如下所示: C:\myApps\Application1\Documents\Project\Project1
我希望额外的反斜杠可以转义我实际需要的反斜杠,这样我的组合路径看起来很正常,没有双反斜杠。

更新:
我想我一直都被调试器欺骗了。有人可以确认调试器将始终显示一个包含 \'s 的字符串作为 \\

这样试试:

string documentPath = @"C:\myApps\Application1\Documents\Project";
string projectName = "Project1";
string combinedPath = System.IO.Path.Combine(documentPath, projectName);

您可以简单地使用示例中使用的 @ Verbatim literal 而不是转义序列 \

方法一:有弱点

您可以使用 + 字符串连接 (msdn)

string documentPath = @"C:\myApps\Application1\Documents\Project\";
string projectName = "Project1";

string fullpath = documentPath + projectName;

Console.WriteLine(fullpath);

方法二:推荐方式

一旦你使用了@Verbatim literal,你可以简单地使用Path.Combine()

Console.WriteLine(System.IO.Path.Combine(documentPath,projectName));

正如评论和其他答案中指出的那样,使用 Path.Combine() 是更好的方法。

输出:

C:\myApps\Application1\Documents\Project\Project1 // <= From + concatenation 
C:\myApps\Application1\Documents\Project\Project1 // <= From path Combine

另外 : 转义序列表示 (Source)

字符串转义序列

At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string @"C:\files.txt" will appear in the watch window as C:\files.txt.

您可以通过多种不同的方式执行此操作,但是如果我们使用您当前的方法,您的组合 Path.Combine 将输出正确的路径。

var path = "C:\Example\";
var dir = "Demo";
var combine = Path.Combine(path, dir);

//Output:
C:\Example\Demo

另一种方法是简单地使用 @ 运算符,它会减少创建原始路径时对反斜杠的任何要求。因此,您将拥有:

而不是上述内容
var path = @"C:\Example";

然后当您执行 Path.Combine 时,代码也会按预期工作。我想说要避免的唯一方法是串联。

  • 连接:在内存中创建一个新实例,每次执行。
  • 连接:代码可能很难排除故障(尤其是当您在某处出错时),因为路径的组合几乎没有表现力。