Monday, 4 April 2011

Useful Isolated Storage Tips #1

I had been very curious about IsolatedStorage in WP7 which is mentioned very much in application usage during the P7 workshops. basically it has been around in the framework for a long time, and it stores data in a file that us isolated by the user and by assembly for usage to minimise in such a way that another application cannot use that data.

The good thing about IsolatedStorage is that it is persistent in the application meaning it is permanent in storage, and can be used countless times, which is great, but used sparingly if possible as WP7 does not have an imposed quota size meaning it will continue using the phones storage until it can potentially run out, although it will give a warning when the WP7 phone has 10% of storage left.

Here are some code samples for IsolatedStorage for a text file: -

Saving New Text File To Isolated Storage

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

//create new file

using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("myFile.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))

{

string someTextData = "This is some text data to be saved in a new text file in the IsolatedStorage!";

writeFile.WriteLine(someTextData);

writeFile.Close();

}

Writing to Existing Text File In Isolated Storage

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

//Open existing file

IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("myFile.txt", FileMode.Open, FileAccess.Write);

using (StreamWriter writer = new StreamWriter(fileStream))

{

string someTextData = "Some More TEXT Added:  !";

writer.Write(someTextData);

writer.Close();

}

Reading Existing Text File In Isolated Storage

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("myFile.txt", FileMode.Open, FileAccess.Read);

using (StreamReader reader = new StreamReader(fileStream))

{    //Visualize the text data in a TextBlock text

this.text.Text = reader.ReadLine();

}

Deleting Text File In Isolated Storage

Use IsolatedStorageFile.DeleteFile.

using(var store = IsolatedStorageFile.GetUserStoreForApplication()) 
    store.DeleteFile("myFile.txt");

No comments: