如果创建不存在的.txt文件,如果它不添加一个新行

问题描述:

我想创建一个.txt文件,并写入它,如果该文件已经存在,我只是想多一些行追加:

I would like to create a .txt file and write to it, and if the file already exists I just want to append some more lines:

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(); 
}

但第一线似乎永远会被覆盖......我怎么能避免写在同一行(我在循环中使用这个)?

But the first line seems to always get overwritten... how can I avoid writing on the same line (I'm using this in a loop)?

我知道这是一个pretty简单的事情,但我从来没有使用过的的WriteLine 方法。我完全新的C#。

I know it's a pretty simple thing, but I never used the WriteLine method before. I'm totally new to C#.

使用正确构造

else if (File.Exists(path))
{
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("The next line!");
    tw.Close(); 
}