Skip to content

Save User Data In Silverlight

May 20, 2009

So I’m writing a little time wasting game that step-father 2.0 came up with.  It’s a sort of sudokuesque columns blend.  Of course we want to have a way to keep track of your top ten scores for bragging rights. 

Anyway, in Silverlight you get, to start out, ten megs of isolated storage on each user’s drive to work with.  You can prompt them for more space if you like but for our purposes we’ve got plenty of room for a little text file to store the top ten scores.   private

void SaveScore() {

List<double> scores = new List<double>();

string rawScores = LoadData(“scores.dat”);

/* If there are scores, read them in */

if(rawScores.Length > 0) {

string[] splitScores = rawScores.Split(‘;’);

scores = splitScores.Select(a => double.Parse(a)).ToList();

}

scores.Add(score);

/* Get the scores in order highest to lowest */

scores.Sort((a,b) => b.CompareTo(a));

/* Take the new top ten and semicolon delimit them */

string newScores =

scores.Take(10).Aggregate(“”, (a,b) => (a + “;” + b)).TrimStart(‘;’);

SaveData(newScores, “scores.dat”);

}

And the supporting methods..

private

 

void SaveData(string data, string fileName) {

using (IsolatedStorageFile isf =

IsolatedStorageFile.GetUserStoreForApplication()) {

using (IsolatedStorageFileStream isfs =

new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) {

using (StreamWriter sw = new StreamWriter(isfs)) {

sw.Write(data);

sw.Close();

}}}}

private

 

string LoadData(string fileName) {

string data = String.Empty;

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) {

using (IsolatedStorageFileStream isfs =

new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, isf)) {

using (StreamReader sr = new StreamReader(isfs)) {

string lineOfData = String.Empty;

while ((lineOfData = sr.ReadLine()) != null)

data += lineOfData;

}}}

return data;

}

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: