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

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

问题描述

我想在 textbox 中编写类似 C:UsersUserNameDocumentsTasks 的内容:

I want to write something like this C:UsersUserNameDocumentsTasks in a textbox:

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

我收到错误:

无法识别的转义序列.

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

How do I write a backslash in a string?

推荐答案

反斜杠 ("") 字符是一种特殊的转义字符,用于指示其他特殊字符,例如换行符 ("")> )、制表符 ( ) 或引号 (").

The backslash ("") character is a special escape character used to indicate other special characters such as new lines ( ), tabs ( ), 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天全站免登陆