Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving simple user preferences on Windows Forms with C#

I'm writing my first Windows Forms application using VS 2010 and C#. It does not use a database but I would like to save user settings like directory path and what check boxes are checked. What is the easiest way to save these preferences?

like image 347
Paul Avatar asked Jun 07 '11 11:06

Paul


People also ask

How can I save application settings in a Windows Forms application?

A simple way is to use a configuration data object, save it as an XML file with the name of the application in the local Folder and on startup read it back.

Where are Windows Forms settings stored?

For a Windows Forms-based application copied onto the local computer, app.exe. config will reside in the same directory as the base directory of the application's main executable file, and user. config will reside in the location specified by the Application. LocalUserAppDataPath property.


2 Answers

I suggest you to use the builtin application Settings to do it. Here is an article talking about it.

Sample usage:

MyProject.Properties.Settings.Default.MyProperty = "Something";
like image 50
Erick Petrucelli Avatar answered Sep 23 '22 02:09

Erick Petrucelli


You can use the serializable attribute in conjunction with a 'settings' class. For small amount of information this is really your best bet as it is simple to implement. For example:

  [Serializable]
  public class MySettings  
  {
    public const string Extension = ".testInfo";

    [XmlElement]
    public string GUID { get; set; }

    [XmlElement]
    public bool TurnedOn { get; set; }

    [XmlElement]
    public DateTime StartTime { get; set; }

    public void Save(string filePath)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(MySettings));
      TextWriter textWriter = new StreamWriter(filePath);
      serializer.Serialize(textWriter, this);
      textWriter.Close();
    }

    public static MySettings Load(string filePath)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(MySettings));
      TextReader reader = new StreamReader(filePath);
      MySettings data = (MySettings)serializer.Deserialize(reader);
      reader.Close();

      return data;
    }
  }

There you go. You can prety much cut and paste this directly into your code. Just add properties as needed, and don't forget the [XMLElement] attribute on your interesting properties.

Another benefit to this design is that you don't have to fiddle with the cumbersome Application.Settings approaches, and you can modify your files by hand if you need to.

like image 34
A.R. Avatar answered Sep 27 '22 02:09

A.R.