1

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
Wojtek
  • 801
  • 1
  • 9
  • 13

3 Answers3

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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.

csharpwinphonexaml
  • 3,659
  • 10
  • 32
  • 63
0

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.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184