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.

3 Answers 3

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);
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

what library should I add for Logger?
Regret. I should use another method, because I need not to install new software for this task.
just ignore the Logger part. Its not necessary
I should serialize every object of Question or can I just write into file Dictionary<int, Question> questions = new Dictionary<int, Question>()? And how to use LoadObject method? It doesn't return anything.
No just serialize the whole dictionary
|
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;
        }
    }

3 Comments

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.
And I can't call method Save. Please, show full example
Can I save just save Dictionary<int, Question> questions = new Dictionary<int, Question>() instead of every object?
-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.

2 Comments

Dictionary<TKey, TValue> is serializable.
Well, I stand SOMEWHAT corrected. You can serialize a Dictionary<TKey, TValue> 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: stackoverflow.com/questions/495647/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.