0

My program(in WinForms) is some kind of testing of some subject. I have such structure, where I save my questions of this test:

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

I want to keep my questions(exactly Dictionary<int, Question> questions = new Dictionary<int, Question>();) in binary file and every time I start the program, it will read from this. I've never worked with binary files.

Steve Danner
  • 21,818
  • 7
  • 41
  • 51
user3528837
  • 65
  • 1
  • 2
  • 10

3 Answers3

2

You can serialize the object and save it in a file. But you have to mark your class with [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);
    }
}
Matt Kleinsmith
  • 1,017
  • 3
  • 13
  • 24
TamerM
  • 722
  • 7
  • 25
0

Well you can do that using serialization so check the following code:

   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;
        }
    }
yazan
  • 600
  • 7
  • 12
  • Can you also write an example, where you call these two functions. Cause, I am a bit confused. For example, I want to call Load function in Constructor. And method Save in the FinishButton_Click method. – user3528837 Apr 21 '14 at 12:56
  • And I can't call method Save. Please, show full example – user3528837 Apr 21 '14 at 13:27
  • Can I save just save Dictionary questions = new Dictionary() instead of every object? – user3528837 Apr 21 '14 at 17:15
-1

You are wanting to serialize your objects using the BinaryFormatter class. This SO post will give you the code you need to accomplish this. But be aware that Dictionary<TKey, TValue> is NOT serializable, so you will not be serialize it directly. Instead, consider using List<KeyValuePair<int, Question>> to accomplish the same thing.

Community
  • 1
  • 1
Steve Danner
  • 21,818
  • 7
  • 41
  • 51
  • [`Dictionary`](http://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx) *is* serializable. – User 12345678 Apr 21 '14 at 12:17
  • Well, I stand SOMEWHAT corrected. You can serialize a `Dictionary` in binary format, but not to XML. I personally have run up against this in the past, which prompted my warning. Here is more detail on it, though: http://stackoverflow.com/questions/495647/serialize-class-containing-dictionary-member – Steve Danner Apr 21 '14 at 12:41