Why does my StreamWriter overwrite my whole .txt file?

389 views Asked by At

I'm changing a value within my text, but instead, it's overwriting my whole .txt file with nothing.

static void editClassMates(classMates[] classMateInfo)
{
    StreamWriter sw = new StreamWriter(@"C:\Users\Callum\Documents\class.txt");
    Console.Write("Who's number would you like to change? ");
    string classMateInput = Console.ReadLine();
    for (int i = 0; i < classMateInfo.Length; i++)
    {
        if (classMateInfo[i].last.Equals(classMateInput))
        {
            Console.Write("Enter new number: ");
            string temp = Console.ReadLine();
            int classMateNumber = Convert.ToInt32(temp);
            classMateInfo[i].ID = classMateNumber;
        }   
    }
    sw.Close();
}

My code asks for a name within my .txt file. Once I have specified the name, it loops through until my input matches the same exact name in my .txt file. I now want to change his/her number. After I input a number, I then have a method that displays the list and the change I have made. That works, it shows me my original data along with the value I've edited.

However, I go into my class.txt file and it's completely blank now.

My question is, what part of my code is overwriting my whole file? Also, how can I properly change/edit/replace a specific value inside my .txt file?

Thanks

1

There are 1 answers

5
AudioBubble On
new StreamWriter(@"C:\Users\Callum\Documents\class.txt", true)

You are not using the overload to append. This is easily viewed in Intellisense as you type.

Hint: The File.Open-Method is even more easy to use. Topic in this SO article