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.
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.
And then in the Out-of-Browser Settings, check the elevated trust when run in out-of-browser mode.
Now in App.xaml.cs let's subscribe the CheckAndDownloadUpdateCompleted event to have the notification that a newer version is available.
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.
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.
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:
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.
Now restart the application to see the Local files in the TreeView.
As you expand the Nodes, you can see the contents of the folder.
That's it, we have successfully accessed the Local file System in a trusted application in Silverlight 4.
Hope this article helps.