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.