newbie programmer
newbie programmer

Reputation: 3

alternate way of specifying string path to variable in C#

Is there another way of assigning string path to variable aside from this:

strPath = @"C:\Myfile.txt";

thanks.

Upvotes: 0

Views: 1142

Answers (5)

bkaid
bkaid

Reputation: 52073

string path = Path.Combine("C:", "myfile.txt");

Upvotes: 0

Samuel Neff
Samuel Neff

Reputation: 74899

You can use forward slashes and it'll work fine on Windows and no escaping needed.

strPath = "C:/Myfile.txt";

Upvotes: 2

kervin
kervin

Reputation: 11858

You can use Unicode Escape Sequences....

 string strPath = "C:\u005CMyfile.txt";

Upvotes: 1

Michael
Michael

Reputation: 20049

Do you mean another way of escaping the backslashes?

The @ sign at the start means that the string is treated as a verbatim string literal, and simple escape sequences such as \n or \t are ignored.

If you don't put the @ at the start it is not verbatim, and escape sequences are parsed. If you want to ignore an individual escape sequence you can precede it with a single backslash and it will be ignored.

The reason you would use it in a path such as your example is so that you don't have to escape each individual backslash as you would if you didn't put the @ at the start:

strPath = "C:\\Myfile.txt";

Upvotes: 3

kemiller2002
kemiller2002

Reputation: 115440

You can escape it:

var myPath = "C:\\MyFile.txt"

Upvotes: 4

Related Questions