C# 包含反斜杠的路径字符串的无法识别的转义序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1302864/
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
Unrecognized escape sequence for path string containing backslashes
提问by Kjensen
The following code generates a compiler error about an "unrecognized escape sequence" for each backslash:
以下代码为每个反斜杠生成关于“无法识别的转义序列”的编译器错误:
string foo = "D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
I guess I need to escape backslash? How do I do that?
我想我需要逃避反斜杠?我怎么做?
采纳答案by Brandon
You can either use a double backslash each time
您可以每次使用双反斜杠
string foo = "D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
or use the @ symbol
或使用@符号
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
回答by Piotr Czapla
var foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
回答by Josh
Try this:
尝试这个:
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
The problem is that in a string, a \
is an escape character. By using the @
sign you tell the compiler to ignore the escape characters.
问题是在字符串中, a\
是转义字符。通过使用该@
符号,您可以告诉编译器忽略转义字符。
You can also get by with escaping the \
:
您还可以通过转义\
:
string foo = "D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
回答by Bob Kaufman
string foo = "D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
This will work, or the previous examples will, too. @"..." means treat everything between the quote marks literally, so you can do
这将起作用,或者前面的示例也将起作用。@"..." 意味着从字面上处理引号之间的所有内容,因此您可以这样做
@"Hello
world"
To include a literal newline. I'm more old school and prefer to escape "\" with "\\"
包含文字换行符。我更老派,更喜欢用“\\”来逃避“\”
回答by Scott Weinstein
If your string is a file path, as in your example, you can also use Unix style file paths:
如果您的字符串是文件路径,如您的示例中所示,您还可以使用 Unix 样式的文件路径:
string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";
But the other answers have the more general solutions to string escaping in C#.
但是其他答案对 C# 中的字符串转义有更通用的解决方案。