1

I have a flag class,(and a simple button to change the flag values) when I stop and restart the program I want to see the changed boolean variables. I did my search on it and I am kind of lost. Right now I have a constructor but I couldn't figure how to use it with save/load functions.

What is the simplest way to do it?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Xml;
namespace SaveReloadDeneme
{
    [Serializable]
    public partial class Form1 : Form
    {
        bool flag;
        bool flag2;
        public Form1()
        {
            InitializeComponent();
            flag = false;
            flag2 = false;
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            flag = true;
            flag2 = true;
            Console.WriteLine("Flag changed: " + flag);
            Console.WriteLine("Flag2 changed: " + flag2);
        }



        void SaveData()
        {
            // Create a hashtable of values that will eventually be serialized.
            Hashtable addresses = new Hashtable();
            addresses.Add(1, flag);


            // To serialize the hashtable and its key/value pairs,   
            // you must first open a stream for writing.  
            // In this case, use a file stream.
            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, addresses);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
        }


        public void LoadData()
        {
            // Declare the hashtable reference.
            Hashtable addresses = null;

            // Open the file containing the data that you want to deserialize.
            FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                // Deserialize the hashtable from the file and  
                // assign the reference to the local variable.
                addresses = (Hashtable)formatter.Deserialize(fs);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
           }
        private void Button2_Click(object sender, EventArgs e)
        {

        }
}

static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            Form1 f = new Form1();
            f.SaveData();
            f.LoadData(); 

        }

When I open the ".dat" file, it is gibberish and I think does not contain the current saved value of the flag.

Deniz
  • 378
  • 3
  • 16

2 Answers2

1

The serialization and deserialization looks fine. But in your Main() method, you first save the data and than reload the saved (default) data. So you overwrite the saved data.
Adapting your code would give:

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);        
        Form1 newForm = new Form1();           
        newForm.LoadData(); 
        Application.Run(newForm);
    }

You also save the data before it is changed. The SaveData() method would be better before closing the application. So extending or previous code would be:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);  
    Form1 newForm = new Form1();           
    newForm.LoadData(); 
    Application.ApplicationExit += (o, e) => newForm.SaveData();      
    Application.Run(newForm );
}
Stef Geysels
  • 1,023
  • 11
  • 27
  • Thank you, but it saves the results in ".dat" file but I can not see it, do you know how to display in a proper format, otherwise I can not see the saved value. – Deniz Jul 17 '19 at 12:03
  • Click the button, close your form and restart it. What is the outcome? You can place a breakpoint after the deserializing (after `addresses = (Hashtable)formatter.Deserialize(fs);`) and see the result by hovering `adresses`. – Stef Geysels Jul 17 '19 at 12:13
  • You can serialize to XML. It is explained in [this](https://stackoverflow.com/a/14663848/2100994) anwer. – Stef Geysels Jul 17 '19 at 12:18
1

As mjwils said, JSON could be a good option.

Here are some axamples.

using System;
using System.IO;
using Newtonsoft.Json;

public class Program
{

    public class Movie
    {
        public string Name { get; set; }
        public int Year { get; set; }
    }

    public static void Main()
    {
        Movie movie = new Movie
        {
            Name = "Bad Boys",
            Year = 1995
        };

        // serialize JSON to a string and then write string to a file
        string json =  JsonConvert.SerializeObject(movie);
        Console.WriteLine(json);
        File.WriteAllText("your.path.here", json);

        string json2 = File.ReadAllText("your.path.here");
        Movie movie2 = JsonConvert.DeserializeObject<Movie>(json);
        Console.WriteLine(movie2.Name);
    }
}
user2809176
  • 1,042
  • 12
  • 29
  • In your code it does not perform the deserialize part. It writes to txt but when I close and open the program flags are not updated. Movie2 is not used says the compiler – Deniz Jul 18 '19 at 12:27
  • @Deniz it is an example how you can write a serialized object to a file, you should replace Movie class with your data (flags in this case). – user2809176 Jul 19 '19 at 08:51