每行对应一个联系人,对吧?您删除联系人的标准是什么?如果您正在寻找姓名和姓氏,您可以这样做。
string line = null;
string Criteria = name + " " lastname;
using (StreamReader reader = new StreamReader("C:\\input"))
{
using (StreamWriter writer = new StreamWriter("C:\\output"))
{
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(Criteria))
continue;
writer.WriteLine(line);
}
}
}
这将读取您的文件并将您想要保留在另一个文件中的所有联系人写入。
但是,如果您想保留同一个文件(或者如果您的联系人信息不止一行)。您可以读取整个文件并将其保存在内存中,删除不需要的文件,然后再次写入文件。
//Method with a class containing the info because informations are on several lines
Contact[] contacts = MethodToRead("filename.txt");
Contact[] filteredContacts = methodFilterContacts(contacts );
foreach(Contact c in filteredContacts)
{
//Call your write method mentionned
Writer.writer(c.name, c.lastname, c.number);
}
//Method if contact on only one line
string[] contactLines = File.ReadAllLines("filename.txt");
string[] filteredContactLines = methodFilterContacts(contactLines );
//This will write everything as is
File.WriteAllLines("filename.txt", filteredContactLines );
That was if you want to keep your text file. As it was suggested earlier, you can use xml to write and read an easier to maintain file. If you know the basics of xml, or up for a little challenge (and have time for it), it might be a better way to go.