我制作了一个示例程序来实现这一点,因此我实际上可以学习如何使用它并将其应用到我的实际项目中。简而言之,我的第一次尝试是将 Person 实例写入文件,但后来我无法用写入的不同实例填充列表(我只能看到第一个写入的实例,并且列表只有一个元素)。所以我想出了将 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
获取所有数据?
编辑:尝试和结果:假设我用 John, Doe, 40 click 填充初始框button1
然后加载另一个, Clark, Kent, 50
如果我写“约翰”,tbSearch
我会看到约翰的完整数据(姓名,姓氏和年龄)如果我填写“克拉克”,我会收到一个字典错误“给定的键不在字典中”