我想创建一个.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#完全不熟悉.
我希望使用此方法明确文本文件
private void writeTextFile(string filePath, string text)
{
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
using (StreamWriter tw = new StreamWriter(filePath))
{
File.WriteAllText(filePath,"");
tw.WriteLine(text);
tw.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误
The process cannot access the file because it is being used by another process.
Run Code Online (Sandbox Code Playgroud)
但这不能在任何地方打开,
请帮我谢谢