我有这段代码,它在我的 Student.txt 中添加了一行,但是,每次我编译并运行代码时,它都会再次执行。我可以添加什么代码以便只添加一次新记录?
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);