将新字符串添加到文件的最后一行

本文关键字:一行 最后 字符串 添加 文件 | 更新日期: 2023-09-27 18:36:44

就像标题所说的那样,我想在文件底部添加一个新字符串,但不知何故,它不起作用。希望有人能帮助我x___x

      private string add(string asd){
        {string filename = "asd.txt";
        StreamReader reader = new StreamReader(filename);
        StreamWriter write = new StreamWriter(filename);
        string input = null;
        while ((input = reader.ReadLine()) != null)
        {
            write.WriteLine(input);
        }
        reader.Close();
        write.WriteLine(asd);
        write.Close();}

将新字符串添加到文件的最后一行

使用 File.AppendAllText

打开一个文件,将指定的字符串追加到该文件,然后关闭该文件。如果该文件不存在,此方法将创建一个文件,将指定的字符串写入该文件,然后关闭该文件。

例:

private string Add(string asd) {
    string filename = "asd.txt";
    File.AppendAllText(filename, asd);
}

您同时写入/读取同一文件。那行不通。您必须创建一个要写入的临时文件。

像这样的事情呢:

private string add(string asd){
{
        string filename = "asd.txt";
        string readText = File.ReadAllText(filename );
        File.WriteAllText(filename , createText + asd);
}