-2

我需要开发一个电话簿。

我将联系人数据写入文本文件并使用控制台。我有哪些选项可以搜索和删除该文本文件中的联系人?

这就是我插入联系人的方式:

public class Writer
{
    public void  writer (string name,string lastname,string number)
    {
        StreamWriter Wrt = new StreamWriter("D:\\Sample.txt",true);
        Wrt.Write(name);
        Wrt.Write(lastname);
        Wrt.Write(number);
        Wrt.Write("#");
        Wrt.Write("");
        Wrt.Close();
    }
}
4

1 回答 1

0

每行对应一个联系人,对吧?您删除联系人的标准是什么?如果您正在寻找姓名和姓氏,您可以这样做。

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.

于 2012-04-18T03:25:17.233 回答