Search code examples
c#streamwriter

C# | StreamWriter keeps replacing the current lines


So I have this application where there are 3 textboxes which ask the user for input. When the user has finished filling out the texboxes, there is a button that stores the input into a class.

Now the idea is that as the user presses the button to store the input a class, the input also gets stored into a textfile. The problem that I am facing now is that whenever a user adds new input, the old input gets replaced in the textfile.

This is the code:

using (StreamWriter txtFile = new StreamWriter(@"C:\Users\Desktop\smtp.txt"))
{
    txtFile.WriteLine(Class_Smtp[Index].SmtpClientName);
    txtFile.WriteLine(Class_Smtp[Index].SmtpPort);
    txtFile.WriteLine(Class_Smtp[Index].SmtpEmailExtension + Environment.NewLine);
}

Any Ideas?

Thank you in advance.


Solution

  • You should append the text

    using (StreamWriter txtFile = new StreamWriter(@"C:\Users\Desktop\smtp.txt", true))
    {
        txtFile.WriteLine(Class_Smtp[Index].SmtpClientName);
        txtFile.WriteLine(Class_Smtp[Index].SmtpPort);
        txtFile.WriteLine(Class_Smtp[Index].SmtpEmailExtension + Environment.NewLine);
    }