Entering a file path as a string in C #

I am writing the following code to read in a file from the specified file (using VS2010 and 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); } 

The compiler complains about the following line:

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

It produces a message: Unknown escape sequence in \ W and \ T

What am I doing wrong?

+4
source share
3 answers

You can use a literal string literal :

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

Either this, or escape the \ character:

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

The problem with your current code is that \ is the escape sequence in the string, and \W , \T are unknown escape files.

+15
source

Change it to:

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

The reason is that it interprets “W” and “T” as escape characters since you used only one “\”.

+3
source

You can also use slashes in windows for this. This saves you from having to strip backslashes.

+1
source

Source: https://habr.com/ru/post/1390843/


All Articles