Says your application downloads some data files and need to save them locally in the client's computer for subsequent uses. Well, Silverlight in partial-trust mode cannot access client's file system directly, because that would seriously compromise the client's computer. So, Silverlight team devised an ingenious solution by creating a sandboxed virtual file system as known as Isolated Storage. As the name implies, each Silverlight application is given an isolated storage for its own use, up to about 1MB in Silverlight 1.1 Alpha. This opens up a lot of good possibilities like saving user settings, temporary files, form inputs, etc. Without further ado, let's see how to save a text file:
Shared Sub StoreIsolatedFile(ByVal path As String, ByVal data As String)
Dim iso As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream As New IsolatedStorageFileStream(path, IO.FileMode.Create, iso)
Using writer As New IO.StreamWriter(isoStream)
writer.Write(data)
End Using
End Using
End Sub
As you can see, the very thing to do is get the isolated storage for the application by calling IsolatedStorageFile.GetUserStoreForApplication(). Then you'll need to create an IsolatedStorageFileStream to create a file and write the data. It's easy, isn't? Note that we don't need to call isoStream.Close() here, because Using...End Using statement will take care of it. Now let's take a look at this snippet on how to read a text file from the storage:
Shared Function ReadIsolatedFile(ByVal path As String) As String
Dim iso As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream As New IsolatedStorageFileStream(path, IO.FileMode.Open, iso)
Using reader As New IO.StreamReader(isoStream)
Return reader.ReadToEnd
End Using
End Using
End Function
Again, firstly we get the isolated storage for the application. And we use IsolatedStorageFileStream to open a file and read its data. The StreamReader is just a wrapper stream to read string more easily. Ok, take a look at how to use above snippets to write some string to test.txt file and read the string back:
StoreIsolatedFile("test.txt", "SilverlightExamples.NET rocks!")
Dim data as String = ReadIsolatedFile("test.txt")
For C# developers, you can use below C# snippets:
public static void StoreIsolatedFile(string path, string data)
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(path, IO.FileMode.Create, iso)) {
using (IO.StreamWriter writer = new IO.StreamWriter(isoStream)) {
writer.Write(data);
}
}
}
public static string ReadIsolatedFile(string path)
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(path, IO.FileMode.Open, iso)) {
using (IO.StreamReader reader = new IO.StreamReader(isoStream)) {
return reader.ReadToEnd;
}
}
}