如何在字符串中写反斜杠(\)? [英] How do I write a backslash (\) in a string?

查看:677
本文介绍了如何在字符串中写反斜杠(\)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文本框中 C:\Users\UserName\Documents\Tasks $ c>:

I want to write something like this C:\Users\UserName\Documents\Tasks in a textbox:

txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\Tasks";

我收到错误:


无法识别的转义序列。

Unrecognized escape sequence.

如何在字符串中写反斜杠?

How do I write a backslash in a string?

推荐答案

反斜杠( \ )字符是特殊的转义字符,用于指示其他特殊字符,例如换行符( \n ),制表符( \t )或引号( \ )。

The backslash ("\") character is a special escape character used to indicate other special characters such as new lines (\n), tabs (\t), or quotation marks (\").

如果要包含反斜杠字符本身,则需要两个反斜杠或使用 @ 逐字字符串:

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string:

var s = "\\Tasks";
// or 
var s = @"\Tasks";

阅读 MSDN文档/ C#规范,其中讨论了使用反斜杠字符和

Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

通常来说来说,大多数C#.NET开发人员倾向于使用 @ 逐字记录在构建文件/文件夹路径时使用字符串,因为它使它们不必一直写双反斜杠,并且可以直接复制/粘贴路径,因此建议您养成做同样的习惯。

Generally speaking, most C# .NET developers tend to favour using the @ verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.

在这种情况下,我实际上建议您使用 Path.Combine 实用程序方法,如 @lordkain的答案,因为您无需担心反斜杠是否已包含在路径,并在合并部分路径时不小心将斜线加倍或完全省略。

That all said, in this case, I would actually recommend you use the Path.Combine utility method as in @lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.

这篇关于如何在字符串中写反斜杠(\)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆