下面是代码。
我想将数组列表数据添加到文本文件中。这时它将插入数据,但是当我添加新数据时,它将覆盖之前的数据并仅添加新的数据,因此我希望它会询问您是否要数据已经存在,您要覆盖或添加,如果不存在,则只需将其添加到文件即可。
using (TextWriter writer = File.CreateText(@"C:\Users\Precision\Desktop\testing\data.txt"))
{
foreach (var obj in dirList)
{
writer.WriteLine(obj);
}
}
Console.WriteLine("Record Saved Successfully...");
答案 0 :(得分:0)
从foreach调用此函数,即foreach(目录列表中的var obj){this.WriteToFile(obj.ToString());}
公共无效WriteToFile(字符串文本) {
string path = path\fileName.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(text);
writer.Close();
}
}
答案 1 :(得分:0)
尝试一下...
string outFile = @"C:\Temp\test.txt";
bool isAppend = true;
ArrayList dirList = new ArrayList();
dirList.Add("foo");
dirList.Add("bar");
dirList.Add("baz");
if(File.Exists(outFile))
{
Console.WriteLine("Output file already exists...");
Console.WriteLine("Type 'x' to overwrite or any other to append.");
ConsoleKeyInfo cki = Console.ReadKey();
isAppend = (cki.Key != ConsoleKey.X);
}
using (StreamWriter writer = new StreamWriter(outFile, isAppend))
{
foreach (var obj in dirList)
{
writer.WriteLine(obj);
}
}
答案 2 :(得分:0)
将您的File.CreateText
更改为File.AppendText