Reputation: 210
My aim is to set the bool values where they left of by reading from txt.
Here is my problem, simply, and step by step;
I set the values to "true" by clicking the set button
In txt file, JSON objects are set to true successfully
I closed and re-run the program
I expect the current bool flags to be "true" from previous run
However they are still false, I there is a problem with "deserialize" Button2_Click_1 is just showing me the current values of the flags. Another point is that in the txt file flags are still true which seems okay.
I changed the order of deserialize and serialize yet nothing changed.
[Serializable]
class Class1
{
public bool flag { get; set; }
public bool flag2 { get; set; }
public Class1()
{
flag = false;
flag2 = false;
}
}
[Serializable]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Class1 c1 = new Class1();
private void Button1_Click(object sender, EventArgs e)
{
c1.flag = true;
c1.flag2 = true;
//deserialize
string json2 = File.ReadAllText("path.txt");
Class1 f2 = JsonConvert.DeserializeObject<Class1>(json2);
//serialize
string json = JsonConvert.SerializeObject(c1);
File.WriteAllText("path.txt", json);
Console.WriteLine(json);
}
private void Button2_Click_1(object sender, EventArgs e)
{
Console.WriteLine("Current Status of Flag1: "+c1.flag);
Console.WriteLine("Current Status of Flag2: " + c1.flag2);
}
Upvotes: 1
Views: 128
Reputation: 564
If you are clicking Button2 without first clicking Button1 when the application starts up, c1 will be false by default since the default value of a boolean is false. if you wish to load the json when you click Button2 please add the following code above Console.WriteLine:
c1 = JsonConvert.DeserializeObject<Class1>(File.ReadAllText("path.txt"));
so that it becomes
private void Button2_Click_1(object sender, EventArgs e)
{
c1 = JsonConvert.DeserializeObject<Class1>(File.ReadAllText("path.txt"));
Console.WriteLine("Current Status of Flag1: "+c1.flag);
Console.WriteLine("Current Status of Flag2: " + c1.flag2);
}
and this should fix your issue
Upvotes: 3