我做了一个示例程序,以便实现这一目标,以便我可以实际学习如何使用它并在我的实际项目中使用它。 简而言之,我的第一次尝试是将Person实例写入文件,但我不能在后面填充一个列表,其中写入了不同的实例(我只能看到第一个写入,列表只有1个元素)。所以我想出了将Person实例保存到字典中,将字典写入文件,然后在添加新元素(Person实例)之前从文件中读取完整字典,但我也无法做到这一点。
假设我有一个班级Person
[Serializable]
public class Person
{
public string name, lname;
public int age;
public void newperson(string name,
string lname,
int age)
{
this.name = name;
this.lname = lname;
this.age = age;
}
}
在我的主要课程中,我有两种方法(诚实地从这里偷走,感谢@Daniel Schroeder @deadlydog)通过二进制格式写入和读取文件。
Person nper = new Person(); //nper, an instance of Person
Dictionary<string, Person> dict = new Dictionary<string, Person>();
const string file = @"..\..\data.bin";
_
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
_
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
我有点理解这种方法,但是,我无法对它们进行编码/修改,这超出了我的知识。
为了测试写作/阅读,我拖了几个文本框和button1
private void button1_Click(object sender, EventArgs e)
{
//saving textboxes to Person instance
nper.newperson(textBox4.Text, textBox5.Text, Convert.ToInt16(textBox6.Text));
//saving that object into a dictionary<string,Person> the key is the name, the object is the Person itself
dict[nper.name] = nper;
//Writting this dict
WriteToBinaryFile(file, dict, true);
}
然后,我拖了几个单独的文本框来检查阅读:
private void button2_Click(object sender, EventArgs e)
{
try
{
//read the file and save all into dict (is this working like I think it should? is dict, getting all the data from file?)
dict = ReadFromBinaryFile<Dictionary<string,Person>>(file);
//write into diferent textboxes the Person properties, for the key that matches with another text box that i fill manually to check
textBox1.Text = dict[tbSearch.Text].name;
textBox2.Text = dict[tbSearch.Text].lname;
textBox3.Text = dict[tbSearch.Text].age.ToString();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
button2_Click
中的是dict
从文件中获取所有数据吗?
编辑:尝试并结果:
假设我填写了初始框
约翰,
DOE,
40
点击button1
然后加载另一个,
克拉克,
肯特,
50
如果我在tbSearch
中写“John”,我会看到John的完整数据(姓名,姓氏和年龄)
如果我填写“Clark”,我会收到字典错误“给出的密钥不在字典中”
答案 0 :(得分:1)
在WriteToBinaryFile(file, dict, false)
中设置append parameter = false。
当第一次调用WriteToBinaryFile方法执行BinaryFormatter时,用一个元素写字典,在第二次尝试写一个带有两个元素的字典但附加到第一次写入时,So BinaryFormatter在尝试反序列化时,读取第一部分包含保存字典,首先用一个键尝试(第一次按一下1)。