D-Lef
D-Lef

Reputation: 1339

How do I build a path containing variables?

I want to create a file into a directory, but the path contains two variables and I get error.

TextWriter tw = new StreamWriter(variable1+ "\" + variable2 + ".txt", true);
tw.WriteLine(textbox.Text);
tw.Close();

Which is the correct format of a path in StreamWriter?

Upvotes: 1

Views: 181

Answers (4)

Jeremy Kalas
Jeremy Kalas

Reputation: 124

Try this

TextWriter tw = new StreamWriter(variable1+ "\\" + variable2 + ".txt", true);

Doing backslash quotation mark is a way of literally writing a quotation mark in a string, so you need to do a double backslash in order to write a single backslash.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

Well you'll have got an error because "\" isn't a valid string literal.

However, you'd be better off using Path.Combine - and also File.AppendAllText:

var file = Path.Combine(variable1, variable2 + ".txt");
File.AppendAllText(file, textBox.Text);

Note that if you did still want to use a writer, you should use a using statement so the file handle is closed even if an exception is thrown.

Upvotes: 8

Daniel Mann
Daniel Mann

Reputation: 58980

You need to escape the \ characters.

Either of these will work:

TextWriter tw = new StreamWriter(variable1+ "\\" + variable2 + ".txt", true);

or

TextWriter tw = new StreamWriter(variable1+ @"\" + variable2 + ".txt", true);

However, it's generally considered better to use Path.Combine to build paths.

Upvotes: 3

SLaks
SLaks

Reputation: 887305

\ is an escape character.

You need to use a verbatim string literal, which doesn't use escape characters:

@"\"

Upvotes: 0

Related Questions