我写了一个应用程序,要求用户提供他们所住的酒店的一些细节,并且文本很幸运地被添加,但如果我添加另一个人,它将覆盖文件中已存在的先前数据。但是,我希望它能保留所有数据输入。
这是我的代码:
hotelName = txt_HotelName.Text;
ratings = txt_HotelRating.Text;
roomsNeeded = txt_RoomsNeeded.Text;
name = txt_UserName.Text;
surname = txt_UserLastname.Text;
contactDetails = txt_ContactDetail.Text;
paymentDetails = txt_PaymentMehthod.Text;
paymentDate = txt_PaymentDate.Text;
using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
{
sw.WriteLine(txt_HotelName + Environment.NewLine + txt_HotelRating + Environment.NewLine + txt_RoomsNeeded +
Environment.NewLine + txt_UserName + Environment.NewLine + txt_UserLastname + Environment.NewLine + txt_ContactDetail +
Environment.NewLine + txt_PaymentMehthod + Environment.NewLine + txt_PaymentDate);
}
MessageBox.Show($"Thank you for using our system {txt_UserName.Text}.", "Thank you", MessageBoxButtons.OK);
所以我想要的是收集所有数据,而不是每次都重写。
答案 0 :(得分:1)
尝试追加文件:
string line = string.Join(Environment.NewLine, new string[] {
ratings,
roomsNeeded,
name,
surname,
contactDetails,
paymentDetails,
paymentDate});
File.AppendAllLines("HotelDocument.txt", new string[] {line});
编辑如果你想整理输入数据,我建议使用字符串插值( C#6.0 )或格式化:
string line = string.Join(Environment.NewLine, new string[] {
$"Ratings: {ratings}",
$"Rooms need: {roomsNeeded}",
$"Name: {name}",
$"Surname: {surname}",
$"Details: {contactDetails}",
$"Payment: {paymentDetails}",
$"Payment Date: {paymentDate}");
答案 1 :(得分:0)
您需要指定一个唯一名称:
using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
因此,而不是“HotelDocument.txt”可能使用当前DateTime
,甚至new Guid()
是100%唯一。如下所示:
var uniqueFileName = new Guid().ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(uniqueFileName))
或者您是否希望在现有的HotelDocument.txt中添加新数据?