Store your settings in isolated storage
Isolated Storage is a place in Windows where .NET is grated read/write permissions by default. It is a physical folder like any other folder and is located somewhere within C:\Documents and Settings\User name\Local Settings\Application Data\IsolatedStorage. You can read more about it here.
This is a good place to store small files like a setting or configuration file, because you have write permission by default. I have created a simple example of a static setting class called SesttingStore that has two properties which it persists to Isolated Storage. You can add all the properties you want, just remember to modify the Load() and Save() method accordingly.
The first time SettingStore is accessed after the application starts, the static constructor calls the Load method, that fills the properties with values previously saved. When you have changed some of the properties and want to save them to Isolated Storage, just call the Save() method.
#region Using
using System.IO;
using System.IO.IsolatedStorage;
#endregion
/// <summary>
/// Reads and writes settings to the Isolated Storage
/// </summary>
public static class SettingStore
{
#region Constructor
static SettingStore()
{
Load();
}
#endregion
#region Properties
private static string _RootFolder;
public static string RootFolder
{
get { return _RootFolder; }
set { _RootFolder = value; }
}
private static int _Interval;
public static int Interval
{
get { return _Interval; }
set { _Interval = value; }
}
#endregion
#region Methods
private const string FILENAME = "settings.ini";
/// <summary>
/// Saves the values to the Isolated Storage.
/// </summary>
public static void Save()
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null))
{
using (StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream(FILENAME, FileMode.Create, isoStore)))
{
writer.WriteLine(_RootFolder);
writer.WriteLine(_Interval);
}
}
}
/// <summary>
/// Loads the settings from Isolated Storage if they exist.
/// </summary>
private static void Load()
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null))
{
if (isoStore.GetFileNames(FILENAME).Length > 0)
{
using (StreamReader reader = new StreamReader(new IsolatedStorageFileStream(FILENAME, FileMode.OpenOrCreate, isoStore)))
{
_RootFolder = reader.ReadLine();
_Interval = int.Parse(reader.ReadLine());
}
}
}
}
/// <summary>
/// Deletes the file to clear the settings.
/// </summary>
public static void Clear()
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null))
{
if (isoStore.GetFileNames(FILENAME).Length > 0)
isoStore.DeleteFile(FILENAME);
}
}
#endregion
}
Enjoy.
Comments
Comments are closed