如果不存在,创build一个.txt文件,如果它附加了一个新行

我想创build一个.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!"); tw.Close(); } } 
 string path = @"E:\AppServ\Example.txt"; File.AppendAllLines(path, new [] { "The very first line!" }); 

另请参阅File.AppendAllText()。 AppendAllLines会为每一行添加一个换行符,而不必自己把它放在那里。

如果文件不存在,两种方法都会创build文件,因此您不必这样做。

  • File.AppendAllText
  • File.AppendAllLines
 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!"); tw.Close(); } } else if (File.Exists(path)) { using(TextWriter tw = new StreamWriter(path)) { tw.WriteLine("The next line!"); tw.Close(); } } 

您实际上不必检查文件是否存在,因为StreamWriter会为您执行此操作。 如果以附加模式打开它,如果该文件不存在,则该文件将被创build,然后您将始终追加并永远不会写入。 所以你的初步检查是多余的。

 TextWriter tw = new StreamWriter(path, true); tw.WriteLine("The next line!"); tw.Close(); 

你只是想以“追加”模式打开文件。

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

  else if (File.Exists(path)) { using (StreamWriter w = File.AppendText(path)) { w.WriteLine("The next line!"); w.Close(); } } 

你可以使用FileStream。 这为你做所有的工作。

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

当您启动StreamWriter时,它将覆盖之前的文本。 你可以像这样使用append属性:

 TextWriter t = new StreamWriter(path, true); 

从微软的文档,你可以创build文件,如果不存在,并追加到它在一次调用File.AppendAllText方法(string,string)

.NET Framework(当前版本)其他版本

打开一个文件,将指定的string附加到该文件,然后closures该文件。 如果该文件不存在,则此方法将创build一个文件,将指定的string写入该文件,然后closures该文件。 命名空间:System.IO程序集:mscorlib(在mscorlib.dll中)

语法C#C ++ F#VB public static void AppendAllText(string path,string contents)参数pathtypes:System.String将指定的string附加到的文件。 内容types:System.String要附加到文件的string。

AppendAllText