如何在不覆盖已经存在的内容的情况下更新文本文件?

问题描述:

我需要将各种客户详细信息保存到纺织品上,我目前能够保存客户信息,但是当我添加新客户的详细信息时,之前的信息会被覆盖。



我的尝试:



I need to save various customer details onto a textile, I am currently able to save customer information however when I add a new customers' details the previous information is overwritten.

What I have tried:

Dim Filenum As Integer = FreeFile()

FileOpen(Filenum, "Z:\Desktop\original.txt", OpenMode.Output)

PrintLine(Filenum, txtBoxFullName.Text & txtBoxFullAddress.Text & txtBoxDateOfBirth.Text & txtBoxEmailAddress.Text & txtBoxPostcode.Text & txtBoxPhoneNumber.Text & txtBoxItemDetails.Text & txtBoxRepairDescription.Text & txtBoxDateOfBirth.Text)

FileClose(Filenum)

MessageBox.Show("Customer/s has been successfully registered")

不要为输出打开它:如果文件存在并专门删除该文件并打开一个新文件:改为使用OpenMode.Append。



但是...我建议不要将数据保存在平面文件中,而是使用定义格式文件,例如CSV,XML或JSON - 后者很容易支持客户列表,并且可以序列化和反序列化整个如果您使用NewtonSoft.JSON,则只需一行代码中的实例列表:您可以通过NuGet包管理器(工具... NuGet包管理器...包管理器控制台)将其添加到您的项目中:

Don't open it for Output: that specifically deletes the file if it exists and opens a new one: use OpenMode.Append instead.

But ... I would suggest that rather than keeping the data in a flat file, use a "defined format" file such as CSV, XML, or JSON - the latter is trivial to support a list of customers and can serialize and deserialize the entire list of instances in a single line of code if you use NewtonSoft.JSON: you can add it to your project via the NuGet Package Manager (Tools ... NuGet Package Manager ... Package Manager Console):
PM> Install-Package Newtonsoft.Json

然后只需要一行代码完成所有工作:

And then just one line of code does all the work:

File.WriteAllText(path, JsonConvert.SerializeObject(MyCustomers));



And

MyCustomers =  JsonConvert.DeserializeObject<List<Customer>>(File.ReadAllText(path));



另外,您可以获得可直接在许多其他应用程序中使用的文件格式。


Plus, you get a file format that is usable directly in many other applications.