Local File Access in Silverlight 4


Introduction

In Silverlight 4, we have an added feature that allows us to access Local File System. In this article we will see how we can do that.

Creating Silverlight Application

Fire up Visual Studio 2010 and Create a new Silverlight Application, name it as FileAccessSample.

figure1.gif

To access Local File System or we can say specific folders such as Documents, Music, Video, etc... We need to have the application a trusted one. To do so let's enable the Out-of-Browser capabilities.

figure2.gif

And then in the Out-of-Browser Settings, check the elevated trust when run in out-of-browser mode.

figure3.gif

Now in App.xaml.cs let's subscribe the CheckAndDownloadUpdateCompleted event to have the notification that a newer version is available.

figure5.gif

Let's have a TreeView which would display a specific Folder and it's contents.

Now let's install our application first before writing any code for accessing the Folder, otherwise it would throw error saying cannot access local file system.



figure6.gif


Now, let's have a method which will create TreeViewItems and return the TreeViewItem after it is created.

The folder name would be passed as string to the method, based on which the method will decide which folder to access.

figure7.gif
figure8.gif

As you see in above code display, the switch case takes the folderName and based on that it goes to the particular case to access the Special Folder.

You can see, I have used a string array which is being split by '\\' character. Because, the Enumerator returns the full path of the file. So to get rid of that we can use it.

Now in the Load event handler of the MainPage add items to the TreeView, as follows:

figure9.gif

Now build the application, remember you cannot run the application at this point because if we run it is not a trusted application.

So go back to Desktop, where we have a shortcut of our application, run that.

figure10.gif

figure11.gif

Now restart the application to see the Local files in the TreeView.

figure12.gif

As you expand the Nodes, you can see the contents of the folder.

figure13.gif

That's it, we have successfully accessed the Local file System in a trusted application in Silverlight 4.

Hope this article helps.


Similar Articles