将结构保存在二进制文件中,然后从中读取
本文关键字:然后 读取 二进制文件 结构 保存 存在 | 更新日期: 2023-09-27 17:59:15
我的程序(在WinForms中)是对某些主题的某种测试。我有这样的结构,我保存我的问题的这个测试:
Dictionary<int, Question> questions = new Dictionary<int, Question>();
public class Question
{
public Question(string q_text, Dictionary<string, bool> ans)
{
text = q_text;
answers = ans;
}
public string text { get; set; }
public Dictionary<string, bool> answers { get; set; }
}
我想把我的问题(确切地说是Dictionary<int, Question> questions = new Dictionary<int, Question>();
)保存在二进制文件中,每次我启动程序时,它都会从中读取。我从未使用过二进制文件。
您可以序列化对象并将其保存在文件中。但是你必须用[Serializable]标记你的类
using System;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// Persists the object on HD
/// </summary>
public static void PersistObject()
{
Logger.Debug("PersistObject: Started");
// Persist to file
FileStream stream = File.OpenWrite(_filePath);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, objectToSave);
stream.Close();
Logger.Debug("PersistObject: Ended");
}
/// <summary>
/// Loads the object.
/// </summary>
public static void LoadObject()
{
try
{
Logger.Debug("LoadObject: Started");
// Open file to read saved DailyUsers object
if (File.Exists(_filePath))
{
FileStream stream = File.OpenRead(_filePath);
BinaryFormatter formatter = new BinaryFormatter();
object deserializedObject = formatter.Deserialize(stream);
stream.Close();
}
Logger.Debug("LoadObject: Ended");
}
catch (Exception ex)
{
Logger.Error(ex, ex.Message);
}
}
您可以使用序列化来实现这一点,因此请检查以下代码:
Dictionary<int, Question> questions = new Dictionary<int, Question>();
[Serializable]
public class Question
{
public Question(string q_text, Dictionary<string, bool> ans)
{
text = q_text;
answers = ans;
}
public string text { get; set; }
public Dictionary<string, bool> answers { get; set; }
public static void Save(Question q,Stream st)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(st, q);
}
public static void SaveMany(Dictionary<int, Question> questions,Stream st)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(st, questions);
}
public static Question Load(Stream st)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Question q = (Question)bf.Deserialize(st);
return q;
}
public static Dictionary<int, Question> LoadMany(Stream st)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Dictionary<int, Question> q = (Dictionary<int, Question>)bf.Deserialize(st);
return q;
}
}
您想要使用BinaryFormatter类序列化对象。这篇SO文章将为您提供完成此任务所需的代码。但是要注意,Dictionary<TKey, TValue>
是不可序列化的,所以您不会直接序列化它。相反,可以考虑使用List<KeyValuePair<int, Question>>
来完成同样的事情。