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?
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.
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.
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With