C# Can';无法写入txt文件

C# Can';无法写入txt文件,c#,file,C#,File,我正在编写一个程序,该程序读取某些带有名称的.txt文件,然后写入您编写的新数据 文件中的每一行都有名称: 姓 当我添加一个客户并关闭程序时,我可以在customers.txt文件中看到它,但当我再次添加时,它会覆盖现有的已添加客户,而不是在其下创建一个新客户 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; usi

我正在编写一个程序,该程序读取某些带有名称的.txt文件,然后写入您编写的新数据

文件中的每一行都有名称: 姓

当我添加一个客户并关闭程序时,我可以在customers.txt文件中看到它,但当我再次添加时,它会覆盖现有的已添加客户,而不是在其下创建一个新客户

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CustomersList
{
    class Program
    {
        static void Main(string[] args)
        {

            string customers = File.ReadAllText("customers.txt");
            char inp = ' ';

            do
            {
                Console.WriteLine("Pick option!\r\n");
                Console.WriteLine("Add (A)\r\nEnd (E)");
                Console.WriteLine();
                Console.Write("Your option: ");
                Console.Write("");

                inp = Convert.ToChar(Console.ReadLine().ToUpper());

                switch (inp)
                {

                    case 'A':
                        {

                            Console.Write("First Name: ");
                            string fName = Console.ReadLine();
                            Console.Write("Last Name: ");
                            string lName = Console.ReadLine();

                            StreamWriter write = File.CreateText("customers.txt");

                            write.WriteLine(customers);
                            write.Close();
                            AddN(fName, lName);
                            Console.WriteLine();
                            break;
                        }
                }
            } while (inp != 'E');


            Console.ReadKey();


        }

       static void AddN(string nameF, string nameL)
    {
        File.AppendAllText("customers.txt", nameF + " " + nameL.ToString());

    }


}
}
对代码中的更改有什么建议吗?我会很感激的

如果你看一下,你会在备注部分注意到这一点:

此方法等效于StreamWriter(字符串,布尔值) 构造函数重载,将append参数设置为false。如果 路径指定的文件不存在,已创建该文件如果文件没有 存在,其内容将被覆盖。允许附加线程 在文件打开时读取该文件

你想要的是:

创建一个StreamWriter,该StreamWriter将UTF-8编码文本附加到现有的 文件,如果指定的文件不存在,则指向新文件


在线
StreamWriter write=File.CreateText(“customers.txt”)在循环的每次迭代中都要重新创建文件。我建议您将文件的创建移到循环之外

当然,只有在需要/想要创建文件时才创建文件。

file.WriteAllText(路径,文本);
StreamWriter write = File.AppendText("customers.txt");
write.WriteLine(customers);
write.Close();