Thursday, March 17, 2011

Reading And Writing Isolated Storage In Silverlight

http://asimsajjad.blogspot.com/2010/11/reading-and-writing-isolated-storage-in.htmlIn this post I will show you how you can create file on the Isolated Storage and also write on that file and also how can you check the size of the Isolated storage.Isolated storage is a mechanism that allows you to preserve data across browser sessions on a user’s machine. This storage area is tied to an individual user and helps you overcome the 4 KB limitation of a cookie. Unlike a cookie, isolated storage lies outside of the browser cache.
The code which is used to write in the Isolated Storage is listed in List 1.The class used for the Isolated Storage is IsolatedStorageFile which represents an isolated storage area containing files and directories. IsolatedStorageFile class has static method with the name GetUserStoreForApplication which is used to obtains user-scoped isolated storage corresponding to the calling code's application identity. After retrieving the user isolated storage object next step is to create the stream object which is used to write the contains.

using (IsolatedStorageFile isolatedStoragFile = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("MyFileName.txt", FileMode.Append, isolatedStoragFile)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write("Message Date And Time: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") +" -> "+ txtTextToWrite.Text + "\r"); } stream.Close(); } }
List 1

IsolatedStorageFileStream is the class which Exposes a file within isolated storage.IsolatedStorageFileStream is used to read, write and create files in isolated storage. So if you want to read , write or create new file in the Isolated Storage area you need the object of the IsolatedStorageFileStream. I have passed the file name which in this case is .txt extension the, second parameter is the FileMode enumeration which has one of the values as listed in the table given below.The last parameter to the IsolatedStorageFileStream constructor is the IsolatedStorageFile object which is created before.