user8055438
user8055438

Reputation:

How to append text to an existing text file?

I wrote an application that would ask the user for some details of the hotel that they are staying at, and the text does luckily get added, but if I add another person it will override the previous data that was in the file already. However, I want it to keep all of the data inputs.

Here is my code:

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);

So what I want is to collect all of the data, rather than having them over-write each time.

Upvotes: 0

Views: 88

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Try appending the file:

  string line = string.Join(Environment.NewLine, new string[] {
    ratings, 
    roomsNeeded, 
    name, 
    surname, 
    contactDetails, 
    paymentDetails, 
    paymentDate});

  File.AppendAllLines("HotelDocument.txt", new string[] {line});

Edit: if you want to organize the input data, I suggest using string interpolation (C# 6.0) or formatting:

  string line = string.Join(Environment.NewLine, new string[] {
    $"Ratings: {ratings}", 
    $"Rooms need: {roomsNeeded}", 
    $"Name: {name}", 
    $"Surname: {surname}", 
    $"Details: {contactDetails}", 
    $"Payment: {paymentDetails}", 
    $"Payment Date: {paymentDate}");

Upvotes: 1

Jack Marchetti
Jack Marchetti

Reputation: 15754

You need to specify a unique name:

 using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))

So instead of "HotelDocument.txt" maybe use the current DateTime, or even a new Guid() to be 100% unique. So something like:

var uniqueFileName = new Guid().ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(uniqueFileName))

Or are you looking to append new data within the existing HotelDocument.txt?

Upvotes: 0

Related Questions