Wednesday, June 22, 2011

Persistent settings for your Silverlight based WP7 apps

While hacking around with Windows Phone 7 SDK, I realized that there is no easy way to read and write simple app settings with persistent storage. So I wrote a simple class that allows you to encapsulate that behavior and simply development. Hope you find it useful.

To use it follow these steps:
1. Instantiate an object



internal static AppSettings appsettings = new
AppSettings("app_foo_bar.settings");


2. To add key-value pairs


appsettings.settings["iseasy"] = "Easy";


3. To Write to persistant storage


appsettings.WriteSettings();


4. To Read settings on app load


appsettings.ReadSettings();


5. Fetch values


string difficultyLevelSettings = appsettings.settings["iseasy"];




public class AppSettings
{
internal string settingsFileName = "";
public Dictionary settings = new Dictionary();

public AppSettings(string filename)
{
this.settingsFileName = filename;
}

public void ReadSettings()
{
using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var file = appStorage.OpenFile(settingsFileName, FileMode.OpenOrCreate))
{
StreamReader sr = new StreamReader(file);
while (sr.Peek() != -1)
{
try
{
string streasy = sr.ReadLine();
string[] arr = streasy.Split(':');
settings.Add(arr[0], arr[1]);
}
catch
{
}
}
}
}

public void WriteSettings()
{
using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var file = appStorage.OpenFile(settingsFileName, FileMode.OpenOrCreate))
using (var writer = new StreamWriter(file))
{
foreach (var key in settings.Keys)
{
writer.WriteLine(string.Format("{0}:{1}", key, settings[key]));
}
}
}
}

No comments: