-1

I have a trouble with the following code. It should prevent overwriting records in the text file. My code is like that:

    public static void WritingMethod()
    {

    StreamWriter Sw = new StreamWriter("fileone.txt", true);
    string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
    + Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
    // I using the Environment.NewLine to insert new lines
    Console.WriteLine(output);      
    Sw.WriteLine(output + Environment.NewLine);

    Sw.Close();

}

It overwrites the records. I want to add records and not overwrites it.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Mina Hafzalla
  • 2,681
  • 9
  • 30
  • 44
  • 1
    I find that very hard to believe. Change the name of the file and output `DateTime.Now`. I suspect the file is being created (appended) somewhere else. Probably the project's bin\debug or bin\release directory. – Jim Mischel Apr 26 '13 at 01:05
  • 1
    Most likely error is somewhere else as your current sample behaves exactly as you want - appends lines to file. Side note: please use `using` instead of `.Close` as it leads to more readable and correct code (i.e. close file on exception properly). – Alexei Levenkov Apr 26 '13 at 01:05

1 Answers1

4

Open your StreamWriter using File.AppendText:

using (StreamWriter Sw = File.AppendText("fileone.txt"))
{
    string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
    + Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);

    Console.WriteLine(output);      
    Sw.WriteLine(output + Environment.NewLine);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 1
    The constructor he's calling appends the file if the second parameter is `true`. `AppendText` calls that constructor . . . – Jim Mischel Apr 26 '13 at 01:02
  • 1
    Note that your suggestion is identical to original code - both open writer for append - so while yours is correct, the original should behave the same. – Alexei Levenkov Apr 26 '13 at 01:03