C# 向字符串添加反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16899522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add backslash to string
提问by misha312
I have a path and I want to add to it some new sub folder named test. Please help me find out how to do that. My code is :
我有一个路径,我想向其中添加一些名为 test 的新子文件夹。请帮我找出如何做到这一点。我的代码是:
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(path+"\test");
The result I'm getting is : "c:\Users\My Name\Pictures est"
我得到的结果是:“c:\Users\My Name\Pictures est”
Please help me find out the right way.
请帮我找出正确的方法。
采纳答案by Steve
Do not try to build pathnames concatenating strings. Use the Path.Combinemethod
不要尝试构建连接字符串的路径名。使用Path.Combine方法
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(Path.Combine(path, "test"));
The Path classcontains many useful static methods to handle strings that contains paths, filenames and extensions. This class is very useful to avoid many common errors and also allows to code for a better portability between operating systems ("\" on win, "/" on Linux)
在Path类包含了许多有用的静态方法来处理包含路径,文件名和扩展名字符串。此类对于避免许多常见错误非常有用,并且还允许编写代码以实现操作系统之间更好的可移植性(win 上的“\”,Linux 上的“/”)
The Path class is defined in the namespace System.IO.
You need to add using System.IO;to your code
Path 类在命名空间中定义System.IO。
您需要添加using System.IO;到您的代码
回答by Moo-Juice
You need escape it. \tis an escape-sequence for Tabs 0x09.
你需要逃避它。 \t是 Tabs 的转义序列0x09。
path + "\\test"
path + "\\test"
or use:
或使用:
path + @"\test"
path + @"\test"
Better yet, let Path.Combinedo the dirty work for you:
更好的是,让我们Path.Combine为你做一些肮脏的工作:
Path.Combine(path, "test");
Path.Combine(path, "test");
Pathresides in the System.IOnamespace.
Path驻留在System.IO命名空间中。
回答by Greg Dietsche
There are two options:
有两种选择:
- Use the @ symbol e.g.: path + @"\test"
- use a double backslash e.g.: path + "\\test"
- 使用@ 符号,例如:path + @"\test"
- 使用双反斜杠,例如:path + "\\test"
回答by tafa
Backslash '\'is an escape character for strings in C#.
You can:
反斜杠'\'是 C# 中字符串的转义字符。你可以:
use
Path.CombinePath.Combine(path, "test");escape the escape character.
Console.WriteLine(path+"\test");use the verbatim string literal.
Console.WriteLine(path + @"\test");
用
Path.CombinePath.Combine(path, "test");转义转义字符。
Console.WriteLine(path+"\test");使用逐字字符串文字。
Console.WriteLine(path + @"\test");
回答by trinalbadger587
string add;
字符串添加;
add += "\"; //or :"\" means backslash
回答by trinalbadger587
the backslash is an escape character, so useConsole.WriteLine(path+"\\test");
orConsole.WriteLine(path+@"\test");
反斜杠是一个转义字符,所以使用Console.WriteLine(path+"\\test");
或Console.WriteLine(path+@"\test");

