我有這段代碼,它向我的Students.txt中添加了一行代碼,但是,每次我編譯並運行代碼時,它都會再次執行代碼。我可以添加哪些代碼,以便只添加一次新記錄?如何僅將一個值添加到我的txt文件中?
string newLastName = "'Constant";
string newRecord = "(LIST (LIST 'Constant 'Malachi 'D) '1234567890 '[email protected] 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);
每次運行你想重新寫一遍或想追加它? –