File Access Option

In Silverlight there are 3 main ways of accessing files:

  • OpenFileDialog and SaveFileDialog – This is the most flexible of all the file access options as this can be used by any Silverlight application running at any permission level. The user can select any file as long as the user has permissions for the same. The user will have to select the file to read and while saving the user has to specify the filename to override or save as. The code has no permission to know the location of the file and unless the code has elevated permissions the path of the file cannot be known rather only the filename is available. The ability to know the exact path or location is considered to be a security risk by Silverlight. Also these File dialogs are also not allowed until the code for these dialogs is being run in an event handler for user input.
  • FileStream, StreamWriter – The second way is to use the different classes in the System.IO namespace. Silverlight offers classes like File, FileInfo, Directory, DirectoryInfo, FileStream, StreamWriter, etc. In these operations user is not involved. This mode of operation is available only for the trusted application. Not all Silverlight applications can use unless the application is running under elevated privileges.
  • Isolated Storage – A Silverlight application can read or write files to the Isolated Storage without needing the user to be involved. The files can be read or written. The only catch is that the files are saved in the private storage which is under the user directory and the path is not available. So you can just use it as a private store of files where you can access the files. There is no access available for the user files and neither the user can look at the files that are saved unless the user looks into the most of the hidden folder and files under their directory. So the main purpose of Isolated Storage is to provide the application the fast and easy access of files store without user input or elevated trust. But this storage is not reliable as the user can always delete the files.

Let’s have a look at each of these File Access methods in detail:

SaveFileDialog

The SaveFileDialog uses the same file save dialog box supplied by the operating system. To use it we need to create an instance of the SaveFileDialog and call the ShowDialog method. It returns true or false depending on whether the user selected a file or not. The return type of ShowDialog method is nullable bool so we need to compare the return value of the ShowDialog method with true to proceed further with the file selected. However the ShowDialog never returns null but this is the way it is designed. As you can see in the image below once we verify that the user has a selected a filename we can open the file. We can get the filename of the file from the SaveFileName property but the path is not available. So the only way write data is to write the string returned by the dialog.

 

Silverlight 4 : Save File Dialog

Silverlight 4 : Save File Dialog

From the perspective of .Net this is only a string which we can put in a StremWriter to write text into it. If we want to write binary data into it then we can use the Stream Object directly. We can browse to the selected folder and have a look at the saved file.

OpenFileDialog

The OpenFileDialog is similar to the SaveFileDialog. The major difference being  that FileOpenDialog offers a property called multi select which when set to true the user can choose multiple files. So the OpenFileDialog being more complex does not offer a OpenFile method. So depending on whether the OpenFileDialog is in single file or multi file mode we need to use the File or Files property respectively. So as we see in the image below we call File.OpenRead as we are dealing with single file. In the multi select mode we would use the Files property which would return a collection of FileInfo object.

 

Silverlight 4 : Open File Dialog

Silverlight 4 : Open File Dialog

FileStream

The usage of FileStream is quite similar to the regular .NET File access using FileStream. However in Silverlight only application running in elevated trust are allowed to use this technique which is available only in Out of Browser mode. Another restriction in Silverlight is that the files only in specific folder location are available using FileStream. The accessible files are the ones which are in the Users Documents, Music, Pictures and Videos. The reason is because Silverlight runs on multiple platforms and the file system on these platforms might be different and location of these folders might be different on different platforms. We need to use the Enviorment.GetFolderPath method to access these folders. We can also inspect the directory structure beneath these folders using the Directory and DirectoryInfo class in System.IO.

Isolated Storage

It provides storage associated with the logged in user. The API presents data from the stream class from the System.IO namespace. This storage can be used to store either text or binary data. It’s called as Isolated as the storage is partitioned and the Silverlight application have access only to specific parts. Firstly, the storage is partitioned as per the user so that the apps do not have access to the storage space allocated to the other user of the machine. Secondly, the storage is partitioned as per the site and optionally as per the application in the site as well. The partition of the isolated storage depends on the xap files that the apps access. The isolated storage is not dependent on the hosting page. If the multiple pages of an application access the same xap then they will share the same isolated storage. This works for a multi-site website as well. So if multiple sites download the same xap file then the Silverlight supplication will have access to the same Silverlight application isolated store. The Silverlight application provides 1MB of space by default for each user. If the application has more space requirement then it can ask the user for it. Isolated storage is available across browsers on the same machine similar to sharing the cookies across all bowsers, it takes the cross platform support to whole new level.

 

You might be surprised to know that Silverlight is not the pioneer of isolated storage. It was introduced in Widows forms to store data from the web in the partial trust scenarios. Although the method of access is different and there is no way to access the full .Net framework featured Isolated storage.

Now let’s see how to Write to the Isolated storage. Add the following to your Silverlight application.

try

{

//Obtaining the isolated storage from the user

using (IsolatedStorageFile isoStore =

IsolatedStorageFile.GetUserStoreForApplication())

{

//Create new file

using (IsolatedStorageFileStream isoStream =

new IsolatedStorageFileStream(“MyData.txt”,

FileMode.Create, isoStore))

{

//write some content to the file

using (StreamWriter writer = new StreamWriter(isoStream))

{

//Writing line to the file

writer.WriteLine(“Isolated storage is a cool feature”);

}

}

}

}

catch { }

 

As you would see that we need to begin by asking the user specific store for the application. We can also get the user store shared by all the application on the site by calling GetUSerStoreForSite(). The method returns the directory. Then we create an IsolatedStorageFileStream and the constructor requires the IsolatedStorgaeFile as one of the inputs. So here we create a new file in the store but we do not know the location of it. Then we wrap the IsolatedStorageFileStream into a StreamWriter and we write to that file.

Reading from the Isolated storage is very similar with 3 changes. FileMode.Open instaed of FileMode.Create, StreamReader instead on StreamWriter and reader.ReadLine instead of writer.WriteLine.

 

try

{

//Obtaining the isolated storage from the user

using (IsolatedStorageFile isoStore =

IsolatedStorageFile.GetUserStoreForApplication())

{

//Create new file

using (IsolatedStorageFileStream isoStream =

new IsolatedStorageFileStream(“MyData.txt”,

FileMode.Open, isoStore))

{

//write some content to the file

using (StreamReader reader = new StreamReader(isoStream))

{

//Writing line to the file

String sb = reader.ReadLine();

_isolatedStorageReadText.Text = “Read from UserData.txt: ” + sb;

}

}

}

}

catch { }

 

Deleting from the Isolated Storage. To delete the file from the Isolated we do not need to wait on the user. We can use the code below to do that.

try

{

//obtain the Isolated Storage for the user

using (IsolatedStorageFile isoStore =

IsolatedStorageFile.GetUserStoreForApplication())

{

//Delete

isoStore.DeleteFile(“UserData.txt”);

}

}

catch { }

 

Increase the Quota for the Isolated Storage

There is an option for the application to ask for more Isolated Storage space from the user but its not necessary that this space will be provided as its up the user to provide that space. The additional space request should be made at some user input because if its made at any other time then Silverlight will automatically fail the request. This means the extra Quota is only available to the applications with which the user is interacting. The following code can be use to request for additional isolated storage space.

using (var store = IsolatedStorageFile.GetUserStoreForApplication())

{

Int64 spaceToAdd = 5242880;

Int64 curAvail = store.AvailableFreeSpace;

if (curAvail < spaceToAdd)

{

if (!store.IncreaseQuotaTo(store.Quota + spaceToAdd))

MessageBox.Show(“Increase rejected.”);

else

MessageBox.Show(“Increase approved”);

}

else

MessageBox.Show(curAvail.ToString() + “bytes is available”);

}

 

Silverlight 4 : Increase Quota Isolated Storage

Silverlight 4 : Increase Quota Isolated Storage

The users not have the option to wind the quota back as Silverlight does not know which file to trim to remove the quota.

You can download the source code for this file here.

 

Any comments, feedback and questions are most welcome.