Ber*_*eer 150 c# text-files
我想创建一个.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();
}
Run Code Online (Sandbox Code Playgroud)
但是第一行似乎总是被覆盖......我怎么能避免写在同一行(我在循环中使用它)?
我知道这是一件非常简单的事情,但我WriteLine之前从未使用过这种方法.我对C#完全不熟悉.
Dan*_*rth 158
使用正确的构造函数:
else if (File.Exists(path))
{
using(var tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}
}
Run Code Online (Sandbox Code Playgroud)
drc*_*rch 57
string path = @"E:\AppServ\Example.txt";
File.AppendAllLines(path, new [] { "The very first line!" });
Run Code Online (Sandbox Code Playgroud)
另请参见File.AppendAllText().AppendAllLines将为每一行添加换行符,而不必自己将其放在那里.
如果文件不存在,则两种方法都将创建该文件,因此您不必这样做.
小智 40
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!");
}
}
Run Code Online (Sandbox Code Playgroud)
小智 21
您实际上不必检查文件是否存在,因为StreamWriter将为您执行此操作.如果在append-mode中打开它,如果文件不存在则会创建该文件,然后您将始终追加并且永远不会过度写入.所以你的初步检查是多余的.
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("The next line!");
tw.Close();
Run Code Online (Sandbox Code Playgroud)
File.AppendAllText将字符串添加到文件。如果该文件不存在,还将创建一个文本文件。如果您不需要阅读内容,这将非常有效。用例是日志记录。
File.AppendAllText("C:\\log.txt", "hello world\n");
Run Code Online (Sandbox Code Playgroud)
小智 5
您只需使用 File.AppendAllText() 方法即可解决您的问题。如果不可用,此方法将负责文件创建、打开和关闭文件。
var outputPath = @"E:\Example.txt";
var data = "Example Data";
File.AppendAllText(outputPath, data);
Run Code Online (Sandbox Code Playgroud)