相关疑难解决方法(0)

如果不存在,则创建.txt文件,如果它确实附加了新行

我想创建一个.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#完全不熟悉.

c# text-files

150
推荐指数
7
解决办法
40万
查看次数

如何清除文本文件内容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)

但这不能在任何地方打开,

请帮我谢谢

c# streamwriter

4
推荐指数
1
解决办法
4万
查看次数

标签 统计

c# ×2

streamwriter ×1

text-files ×1