2012-01-13 52 views
4

我写了下面的代码从给出的文件路径读取文件(使用VS2010 & C#):键入文件路径为C#中的字符串

static void Main(string[] args) 
    { 
     string temp; 
     string path = "C:\Windows\Temp\fmfozdom.5hn.rdl"; 
     using(FileStream stream = new FileStream(path, FileMode.Open)) 
     { 
      StreamReader r = new StreamReader(stream); 
      temp = r.ReadToEnd(); 
     } 

     Console.WriteLine(temp); 
    } 

编译器抱怨以下行:

string path = "C:\Windows\Temp\fmfozdom.5hn.rdl"; 

它给出了消息:在无法识别的转义序列\ W\ t

我做错了什么?

回答

15

您可以使用verbatim string literal

string path = @"C:\Windows\Temp\fmfozdom.5hn.rdl"; 

要么,或逃避\字符:

string path = "C:\\Windows\\Temp\\fmfozdom.5hn.rdl"; 

与您现有的代码的问题是,\是转义序列字符串中并且\W,\T是未知逃脱。

3

将其更改为:

string path = "C:\\Windows\\Temp\\fmfozdom.5hn.rdl"; 

的原因是,它的解释“W”和“T”作为转义字符,因为你只用一个“\”。

1

您也可以在Windows中使用正斜杠。这将消除转义反斜杠的需要。

相关问题