我已经看到很多例子来解决这个问题,但目前为止还没有任何工作。也许我没有正确地做到这一点。我的代码是:用单个反斜杠代替双反斜杠
private void button1_Click(object sender, EventArgs e)
{
string str = "C:\\ssl\\t.txt";
string str2 = str.Replace("\\","\");
}
我放出来应该是这样的:
C:\ SSL \ t.txt
我已经看到很多例子来解决这个问题,但目前为止还没有任何工作。也许我没有正确地做到这一点。我的代码是:用单个反斜杠代替双反斜杠
private void button1_Click(object sender, EventArgs e)
{
string str = "C:\\ssl\\t.txt";
string str2 = str.Replace("\\","\");
}
我放出来应该是这样的:
C:\ SSL \ t.txt
string str = "C:\\ssl\\t.txt";
这将是输出C:\ssl\t.txt
。由于转义序列,C#将\
字符标记为\\
。
对于转义字符的列表,请访问以下网页:
private void button1_Click(object sender, EventArgs e)
{
string str = "C:\\ssl\\t.txt";
MessageBox.Show(str);
}
你为什么要这么做?为了得到\
\\
,像
string str = "C:\\ssl\\t.txt";
这相当于
string str = @"C:\ssl\t.txt";
尝试输出字符串,你会看到,它是:在C语言中,你必须逃离\
这样实际上
C:\ssl\t.txt
尽管所有其他的答案是正确的,它似乎像OP已经困难理解他们,除非他们使用Directory
或Path
作为示例。
在C#中,\
字符用于描述特殊字符,如\r\n
,它代表一个System.Environment.NewLine
。
string a = "hello\r\nworld";
// hello
// world
正因为如此,如果你想用文字\
,你需要逃避它,使用\\
string a = "hello\\r\\nworld";
// hello\r\nworld
这适用到处,即使在Regex
或Path
小号。
System.IO.Directory.CreateDirectory("hello\r\nworld"); // System.ArgumentException
// Obviously, since new lines are invalid in file names or paths
System.IO.Directory.CreateDirectory("hello\\r\\nworld");
// Will create a directory "nworld" inside a directory "r" inside a directory "hello"
在某些情况下,我们只关心字面\
,所以写\\
所有的时间将变得相当累人,并会使代码难以调试。为了避免这种情况,我们使用逐字字符@
string a = @"hello\r\nworld";
// hello\r\nworld
简短的回答:
没有必要与\
更换\\
。
事实上,你应该不是试一下。
输出将看起来像那样\\是\ – 2013-03-11 12:23:19
的转义字符您不需要替换,您输出的内容将与'C:\ ssl \ t.txt'相同' – Habib 2013-03-11 12:23:41
'“C:\ \ ssl \\ t.txt“'相当于'@”C:\ ssl \ t.txt“',不需要替换任何东西。 – Nolonar 2013-03-11 12:29:55