我想将行添加到我的文件中。我正在使用代码:
StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final);
sw.Dispose();
此刻它正在连续输出所有内容。
答案 0 :(得分:2)
使用sw.WriteLine(the_final);
或sw.Write(the_final + "\n");
但更干净:
System.IO.File.AppendAllText("gamedata.txt", the_final + Environment.NewLine);
答案 1 :(得分:1)
你应该使用writeline写一个新行sw.WriteLine(the_final)
它将行终止符写入文本流
答案 2 :(得分:1)
您可以使用WriteLine()
方法代替Write()
。
答案 3 :(得分:1)
我认为问题在于您将输出构建到变量中:the_final
您需要插入新行。你可以通过以下方式做到这一点:
the_final = "My First Line" + "\r\n";
the_final += "My Second Line!" + "\r\n";
thirdline = "My Third Line!";
the_final += thirdline + "\r\n";
“\ r \ n”将产生您正在寻找的回车。
每个人正在制作的其他建议只会在输出结尾附加1行,其余部分仍在一行中。
答案 4 :(得分:0)
sw.Writeline();
在最后写了一个新行。
sw.Write();
最后不附加新行。
答案 5 :(得分:0)
使用sw.WriteLine()
而不是Write()
MSDN: 将行终止符写入文本流。
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline.aspx
答案 6 :(得分:0)
手动添加换行符
StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final + "\n");
sw.Dispose();
或使用writeline方法
通过简短的谷歌搜索很容易回答这个问题。在发布之前进行一些研究是很好的形式
答案 7 :(得分:0)
虽然其他人已经回答了您的初步问题,但我是否也可以建议这种改进?
using(StreamWriter sw = new StreamWriter("gamedata.txt", true))
{
sw.WriteLine(the_final);
}
当你有一个继承自IDisposable
的对象时,使用using
而不是手动处理它是一种很好的形式。首先,即使遇到异常,using
也会处理您的对象。