我想将文件创建到目录中,但是路径包含两个变量,并且出现错误。
TextWriter tw = new StreamWriter(variable1+ "\" + variable2 + ".txt", true);
tw.WriteLine(textbox.Text);
tw.Close();
StreamWriter中路径的正确格式是什么?
最佳答案
嗯,您会遇到错误,因为"\"
不是有效的字符串文字。
但是,最好使用Path.Combine
-和File.AppendAllText
:
var file = Path.Combine(variable1, variable2 + ".txt");
File.AppendAllText(file, textBox.Text);
请注意,如果您仍然想使用编写器,则应使用
using
语句,以便即使抛出异常也将关闭文件句柄。
关于c# - 如何建立包含变量的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18322160/