如果创建不存在的.txt文件,如果它不添加一个新行 [英] Create a .txt file if doesn't exist, and if it does append a new line

查看:114
本文介绍了如果创建不存在的.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(); 
}

这篇关于如果创建不存在的.txt文件,如果它不添加一个新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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