0

I would like to ask you if anyone of you knows how can I save changes in the progrem so when It will be restarted, the changes would remain?

for example, I have a boolean variable which his defualt value is "false". I want after the inital start, change the value to "true" so when I'll close and start the program, the boolean variable value would be true.

C sharper
  • 104
  • 1
  • 2
  • 9

2 Answers2

0

That's what we have databases for...

or config files

or file systems

You need to retain data, which cant be in memory it has to be on disk

Read about various data persisting strategies try out things and let us know if you are stuck

Muds
  • 4,006
  • 5
  • 31
  • 53
0

Choose format you want to use for persisting you data. On Application starts - read file and deserialize it to your model. On Close - serialize it and save to file. Take a look at next question: Best practice to save application settings in a Windows Forms Application

Next sample was taken from the above link:

using System;
using System.IO;
using System.Web.Script.Serialization;

namespace MiscConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            MySettings settings = MySettings.Load();
            Console.WriteLine("Current value of 'myInteger': " + settings.myInteger);
            Console.WriteLine("Incrementing 'myInteger'...");
            settings.myInteger++;
            Console.WriteLine("Saving settings...");
            settings.Save();
            Console.WriteLine("Done.");
            Console.ReadKey();
        }

        class MySettings : AppSettings<MySettings>
        {
            public string myString = "Hello World";
            public int myInteger = 1;
        }
    }

    public class AppSettings<T> where T : new()
    {
        private const string DEFAULT_FILENAME = "settings.jsn";

        public void Save(string fileName = DEFAULT_FILENAME)
        {
            File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(this));
        }

        public static void Save(T pSettings, string fileName = DEFAULT_FILENAME)
        {
            File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(pSettings));
        }

        public static T Load(string fileName = DEFAULT_FILENAME)
        {
            T t = new T();
            if(File.Exists(fileName))
                t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName));
            return t;
        }
    }
}
Community
  • 1
  • 1
Artiom
  • 7,694
  • 3
  • 38
  • 45