I have this code, which adds a line into my Students.txt, however, everytime I compile and run the code, it does it again. What code can I add so that the new record is only added once?
string newLastName = "'Constant";
string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 'mdconstant@mail.usi.edu 4.000000 )";
string line;
string lastName;
bool insertionPointFound = false;
for (int i = 0; i < lines.Count && !insertionPointFound; i++)
{
line = lines[i];
if (line.StartsWith("(LIST (LIST "))
{
values = line.Split(" ".ToCharArray());
lastName = values[2];
if (newLastName.CompareTo(lastName) < 0)
{
lines.Insert(i, newRecord);
insertionPointFound = true;
}
}
}
if (!insertionPointFound)
{
lines.Add(newRecord); //This record is always added, making the file longer over time
//if it is not deleted each time from the Students.txt file in
} //the bin folder.
File.WriteAllLines("Students.txt", lines);
If what you are writing is known or only to occur in the file once, then first open the file and check if the record-to-be-written exists in the file. If it doesn’t, then proceed to write it, otherwise don’t write it.