Reputation: 831
Suppose I have a file with a name starting with "n" (like "nFileName.doc"). Why is it that when I get its path as a string and print it to the console the "\n" sequence is not treated as an escape sequence (and broader - single backslashes in the path are not treated as escape characters)?
string fileName = Directory.GetFiles(@"C:\Users\Wojtek\Documents").Where(path => Path.GetFileName(path).StartsWith("n")).First();
string str = "Hello\nworld";
Console.WriteLine(fileName); // C:\Users\Wojtek\Document\nFileName.doc
Console.WriteLine(str); //Hello
//world
Upvotes: 1
Views: 395
Reputation: 101701
Because the backslash that comes before the n
is already escaped in your file path. Consider this:
Console.WriteLine("\\n");
This will write \n
to the console because the backslash
is escaped...
In order to verify this debug your program and look at the value of fileName
, you will see that all backslashes are escaped.
Upvotes: 0
Reputation: 3683
Because fileName
will equal
C:\\Users\\Wojtek\\Document\\nFileName.doc
in your code so the n
at the starting of your file name will not be treated as part of any escaped character.
Upvotes: 1
Reputation: 1500835
The concept of escaping is only relevant for source code (and other specific situations such as regular expressions). It's not relevant when printing a string to the screen - Console.WriteLine
doesn't have any such concept as escape sequences.
For example, consider:
string x = @"\n";
This is a string with two characters - a backslash and n
. So when you print it to the screen, you get a backslash and n
.
Upvotes: 5