Adding to text file without deleting

梦想与她 提交于 2019-12-07 19:03:21

问题


I need to add 4 variable numbers into a single line but using the current code it just replaces the numbers thus making it pointless.

using (StreamWriter writer = new StreamWriter("build.txt"))
{
    writer.Write(" " + layer + " " + x + " " + y + " " + block);
    Console.WriteLine("[" + layer + "," + x + "," + y + "," + block + "]");                   
}

so I needed it to write...

 l x y b l x y b l x y b l x y b ...

...but it did not work out like that, and the internet wasn't particularly helpful, hopefully here can help.


回答1:


I would use File.AppendAllText, personally... That way you can just specify the text you want to write, and the method will open the file, append the text, and then close the file.

If you really want to use the writer though, you could use File.AppendText:

using (var writer = File.AppendText("build.txt"))
{
    writer.Write(...);
}

Or you can use the StreamWriter constructor with an append parameter. I'd definitely recommend using the methods in File though - they're much clearer to read.




回答2:


StreamWriter has a constructor that accepts a boolean value to indicate that you want to append to the current text and not overwrite it

using (StreamWriter writer = new StreamWriter("build.txt", true))
{
    .....
}



回答3:


You should use File.AppendText for this:

using (StreamWriter sw = File.AppendText("build.txt")) 
{
   sw.Write(" " + layer + " " + x + " " + y + " " + block);
   Console.WriteLine("[" + layer + "," + x + "," + y + "," + block + "]");
}


来源:https://stackoverflow.com/questions/16366827/adding-to-text-file-without-deleting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!