Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing settings/variables persistantly in C#/.NET

Tags:

c#

.net

settings

Ok, this is a total newb question, so please forgive me.

What is the best way to store variables so that they persist and are recoverable? I have a small application that uses about 10 variables (string and decimal) as settings. Currently, I convert them all to strings, if needed, put them into an array and serialize the array to a file.

This is a pain if I ever want to add a variable. So, I was thinking about using a hashtable and serializing that. Again, not sure what is the best way to do this.

Some requirements I have are that the data needs to be stored securely (encrypted), and must be accessible by other applications (I have two other small apps that read the settings).

I know I am over-complicating something so basic and simple. This must be done in nearly every application built.

TIA

like image 903
robotshapes Avatar asked Jun 04 '10 19:06

robotshapes


2 Answers

The simpliest, effective and most flexible approach is to create a class, add settings, then serialize/deserialize when needed. This source code for the class can be reused in other assemblies, and persistence can be anywhere. Make sure this class knows how to serialize/deserialize itself because of your security requirement. This ensures the implementation stays with the class. Then the calling assembly just needs to create the object by calling a static/shared method.

This gives you strongly-typed settings, versioning, ability to add new settings, and even complex data types (other classes). This object can even be passed to other objects as arguments, and since it supports serialization, it is very flexible.

Example

See How-To (Object Class => Binary Serialization => To Memory => Encrypt => Save to File) at http://social.msdn.microsoft.com/forums/en-US/netfxremoting/thread/68c200c2-4aa4-48dc-95be-6fe077fd10f4/

Reference

  • Version Tolerant Serialization at http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx

  • ISerializable Interface at http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx

  • Isolated Storage at http://msdn.microsoft.com/en-us/library/3ak841sy.aspx

  • Cryptographic Tasks at http://msdn.microsoft.com/en-us/library/7yx4d854.aspx

like image 150
AMissico Avatar answered Sep 25 '22 01:09

AMissico


Use an application/web config file, and use the ConfigurationManager.AppSettings[configurationItemName] method. (in System.Configuration)

like image 45
DaveRead Avatar answered Sep 25 '22 01:09

DaveRead