我想创建一个.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#完全是新手。
发布于 2012-03-28 20:42:41
else if (File.Exists(path))
{
using(var tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}
}
发布于 2013-09-11 21:52:25
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!");
}
}
发布于 2015-06-17 05:46:58
实际上,您不必检查该文件是否存在,因为StreamWriter将为您做这件事。如果你在append-mode中打开它,如果文件不存在,将会被创建,然后你将总是追加,并且永远不会覆盖。所以你的初始检查是多余的。
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("The next line!");
tw.Close();
https://stackoverflow.com/questions/9907682
复制相似问题