Escaping String Literals

by Donn Felker 14. January 2007 11:17

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Donn Felker

Senior Consultant
MCTS
ScrumMaster
Agile Practitioner

About Me | Books I Recommend

Gotta Pay The Bills


Tag cloud

    Popular Posts

    RecentComments

    Comment RSS

    Calendar

    <<  January 2009  >>
    MoTuWeThFrSaSu
    2930311234
    567891011
    12131415161718
    19202122232425
    2627282930311
    2345678

    View posts in large calendar