繁体   English   中英

C#Streamwriter在彼此之间附加文本

[英]c# streamwriter append text under each other

我想在文件中附加行。 我正在使用代码:

StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final);
sw.Dispose();

目前,它连续输出所有内容。

使用sw.WriteLine(the_final); sw.Write(the_final + "\\n");

但是更干净:

System.IO.File.AppendAllText("gamedata.txt", the_final + Environment.NewLine);

您应该使用writeline在新行中sw.WriteLine(the_final)

将行终止符写入文本流

http://msdn.microsoft.com/en-us/library/ebb1kw70.aspx

您可以使用WriteLine()方法代替Write()

我认为问题是当您将输出构造到变量中时: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行,其余部分保持在一行上。

sw.Writeline(); 在末尾写一个新行。 sw.Write(); 在末尾不添加新行。

sw.WriteLine()上使用sw.WriteLine() Write()

MSDN:将行终止符写入文本流。

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline.aspx

手动添加换行符

StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final + "\n");
sw.Dispose();

或使用writeline方法

谷歌搜索很容易回答这个问题。这是在发布之前进行一些研究的好形式

尽管其他所有人都回答了您的第一个问题,但我是否也可以提出这一改进建议?

using(StreamWriter sw = new StreamWriter("gamedata.txt", true))
{
    sw.WriteLine(the_final);
}

当您有一个从IDisposable继承的对象时,最好使用using而不是手动对其进行处理。 一方面,即使遇到异常, using也可以处理您的对象。

使用文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM