将结构保存在二进制文件中,然后从中读取

时间:2014-04-21 12:05:47

标签: c#

我的程序(在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>();),每次启动程序时,都会从中读取。我从未使用二进制文件。

3 个答案:

答案 0 :(得分:1)

您可以序列化对象并将其保存在文件中。但是你必须用[Serializable]

标记你的课程
/// <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);
            }
        }

答案 1 :(得分:0)

您可以使用序列化执行此操作,因此请检查以下代码:

   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;
        }
    }

答案 2 :(得分:-1)

您想要使用BinaryFormatter类序列化对象。 This SO post将为您提供完成此操作所需的代码。但请注意Dictionary<TKey, TValue>不可序列化,因此您不会直接序列化它。相反,请考虑使用List<KeyValuePair<int, Question>>来完成同样的事情。