Reputation: 131
EDIT: I finally managed to write into the file and solved the error, however it does not update the bools, I mean I changed the flag values while program is running, yet it does not change the values.
Main class does not see the changes of flags.
I want to save and reload the class boolean variables where it is left off, I tried to use JSON to write and read variables to txt file. However, neither the code creates a txt file nor writes in it.
(I have a button that changes the values of flags)
I am so confused and I don't know what to do. Can you please help me?
using Newtonsoft.Json; using System.Web.Script.Serialization;
EDITED CODE
[Serializable]
[JsonObject(MemberSerialization.OptIn)]
class Class1
{
public bool flag;
public bool flag2;
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;
Console.WriteLine("Flag changed: " + c1.flag);
Console.WriteLine("Flag2 changed: " + c1.flag2);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Class1 c1 = new Class1();
string json = JsonConvert.SerializeObject(c1);
Console.WriteLine(json);
File.WriteAllText("path.txt", json);
string json2 = File.ReadAllText("path.txt");
Form1 f2 = JsonConvert.DeserializeObject<Form1>(json2);
Console.WriteLine(json2);
Upvotes: 1
Views: 385
Reputation: 305
Your code tries to serialize to much information (it tries to serialize members of the Form
class). You should call JsonConvert.SerializeObject(f)
, and use opt-in serialization so you can control easily which members are serialized.
Upvotes: 1