如何在txt文件中添加新行 [英] How to add new line into txt file

查看:45
本文介绍了如何在txt文件中添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将带有文本的新行添加到我的 date.txt 文件中,但不是将其添加到现有的 date.txt 中,而是应用程序正在创建新的 date.txt 文件..

I'd like to add new line with text to my date.txt file, but instead of adding it into existing date.txt, app is creating new date.txt file..

TextWriter tw = new StreamWriter("date.txt");

// write a line of text to the file
tw.WriteLine(DateTime.Now);

// close the stream
tw.Close();

我想打开 txt 文件,添加一些文本,然后关闭它,然后在单击某些内容后:打开 date.txt,添加文本,然后再次关闭它.

I'd like to open txt file, add some text, close it, and later after clicking something: open date.txt, add text, and close it again.

所以我可以得到:

按钮按下:txt打开->添加当前时间,然后关闭它.另一个按钮按下,txt 打开 -> 在同一行中添加文本OK"或NOT OK",然后再次关闭它.

Button pressed: txt opened -> added current time, then close it. Another button pressed, txt opened -> added text "OK", or "NOT OK" in the same line, then close it again.

所以我的 txt 文件看起来像这样:

So my txt file will look like that:

2011-11-24 10:00:00 OK
2011-11-25 11:00:00 NOT OK

我该怎么做?谢谢!

推荐答案

你可以很容易地使用

File.AppendAllText("date.txt", DateTime.Now.ToString());

如果你需要换行

File.AppendAllText("date.txt", 
                   DateTime.Now.ToString() + Environment.NewLine);

无论如何,如果您需要代码,请执行以下操作:

Anyway if you need your code do this:

TextWriter tw = new StreamWriter("date.txt", true);

第二个参数告诉附加到文件.
检查此处 StreamWriter 语法.

with second parameter telling to append to file.
Check here StreamWriter syntax.

这篇关于如何在txt文件中添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆