← All articles

Escaping String Literals

A simple C# trick: prefix a string with @ to stop escaping backslashes in file paths, plus the one case where it still trips you up.

Donn Felker

Donn Felker

2007.01.14 · 1 min read

I’ve been looking through a lot of “hand me down code” (code that was written awhile ago by someone else) that did a lot of File IO. The code works well, but at times its hard to read the really long file paths that they’re using. As you know, file paths in C# have to be escaped, otherwise the compiler will think that you’re trying to escape a character. So a double backslash actually equates to a single backslash when compiled. This can be cleaned up a bit. Read on brethern…

This is how the file paths look now:

// Current File Paths
string path = “c:\\directory\\folder1\\folder2\\folder3\\somefile.txt”;

To make this cleaner, use the “@” symbol at the beginning of the string literal and it will escape the characters for you.

// New File Path
string path = @”c:\directory\folder1\folder2\folder3\somefile.txt”;

Simple, but a lot of programmers dont know this little time saver.

NOTE: using the @ symbol when you need to included \t or \r, \n will not work. It will interepret the characters just as they are “\n” will print on the screen as “\n” not the new line that you’re probably expecting.

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading