我想创建一个.txt文件并将其写入,如果该文件已经存在,我只想追加一些行:
string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine("The very first line!");
tw.Close();
}
else if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path);
tw.WriteLine("The next line!");
tw.Close();
}
但是第一行似乎总是被覆盖...如何避免在同一行上写(我在循环中使用它)?
我知道这是一件非常简单的事情,但是我以前从未使用过该WriteLine
方法。我是C#的新手。
使用正确的构造函数:
else if (File.Exists(path))
{
using(var tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句