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

编程入门 行业动态 更新时间:2024-10-24 17:27:09
本文介绍了如何在字符串中写入反斜杠 ()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在 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.

更多推荐

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

本文发布于:2023-11-06 14:34:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杠   字符串   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!