Create a .txt file if doesn't exist, and if it

2019-01-12 23:18发布

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)?

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

标签: c# text-files
12条回答
孤傲高冷的网名
2楼-- · 2019-01-12 23:30

When you start StreamWriter it's override the text was there before. You can use append property like so:

TextWriter t = new StreamWriter(path, true);
查看更多
淡お忘
3楼-- · 2019-01-12 23:31

You could use a FileStream. This does all the work for you.

http://www.csharp-examples.net/filestream-open-file/

查看更多
该账号已被封号
4楼-- · 2019-01-12 23:33
string path=@"E:\AppServ\Example.txt";

if(!File.Exists(path))
{
   File.Create(path).Dispose();

   using( TextWriter tw = new StreamWriter(path))
   {
      tw.WriteLine("The very first line!");
   }

}    
else if (File.Exists(path))
{
   using(TextWriter tw = new StreamWriter(path))
   {
      tw.WriteLine("The next line!");
   }
}
查看更多
倾城 Initia
5楼-- · 2019-01-12 23:37
 else if (File.Exists(path)) 
{ 
  using (StreamWriter w = File.AppendText(path))
        {
            w.WriteLine("The next line!"); 
            w.Close();
        }
 } 
查看更多
劫难
6楼-- · 2019-01-12 23:38

Try this.

string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
    using (var txtFile = File.AppendText(path))
    {
        txtFile.WriteLine("The very first line!");
    }
}
else if (File.Exists(path))
{     
    using (var txtFile = File.AppendText(path))
    {
        txtFile.WriteLine("The next line!");
    }
}
查看更多
你好瞎i
7楼-- · 2019-01-12 23:39

You just want to open the file in "append" mode.

http://msdn.microsoft.com/en-us/library/3zc0w663.aspx

查看更多
登录 后发表回答