1

I have a SortedList, the key is Contact.name and the value, is an object, Contact. I´m writing this list to a file, with BinaryWriter and I don´t have any trouble but now I want to read this list, and after, look for an specific contact. I don´t know how to do it. I think that I must read the file and after that look for the contact, but how can I fill the SortedList with the binary code saved in the file?

4

2 回答 2

1

这是一个关于如何从二进制文件读取和写入的快速示例。

static void Main(string[] args)
    {

        WriteContacts(new List<Contact>( new []{ new Contact { ID = 1, Name = "Juan", Age = 34 }, new Contact { Name = "Pedro", Age = 23, ID = 2 } }));
        FindContactInFile("Juan");
        FindContactInFile("Mario");
        Console.ReadKey();
    }

    private static void FindContactInFile(string name)
    {
        IFormatter formatter = new BinaryFormatter();

        using (Stream s = new FileStream("contacts.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var contacts = (List<Contact>)formatter.Deserialize(s);
            var person  = contacts.Where(x=>x.Name==name).FirstOrDefault();
            if (person != null)
                Console.WriteLine("Persona encontrada: {0}", person.Name);
            else
                Console.WriteLine("{0} no fue encontrado en el archivo.", name);
        }
    }

    private static void WriteContacts(List<Contact> contacts)
    {
        IFormatter formatter = new BinaryFormatter();
        using (Stream s = new FileStream("contacts.bin", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(s, contacts);
        }
    }
}
[Serializable]
class Contact
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

那里可以改进许多事情,例如每次搜索某人时不阅读整个文件。或者不立即读取整个文件...无论如何,这里的关键概念是,为了将某些内容存储在二进制文件中,您需要序列化对象。为此,您可以使用 .NET 提供的 BinaryFormatter 之一(正如我在上面所做的那样)并从文件中读取,您只需执行相反的操作。

于 2013-02-28T16:39:10.420 回答
1

听起来像您想要的那样BinaryReader,它将从文件输出中提取BinaryWriter并反序列化为您的原始类型。

这是在 msdn 上同时使用两者的一个很好的例子

于 2013-02-28T16:29:21.890 回答