Read and Write File to Local File System 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 read and write a file to local file system.

Creating Silverlight Application

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

image1.gif

Now we need elevated privilege to access the Local File System to read or write a file from it. So let's enable the out-of-browser mode and enable the elevated privilege for the application.

image2.gif

And of course the elevated privilege in the Out-of-Browser Settings dialog.

image3.gif

Now, let's have two textboxes and two buttons for the purpose of reading and writing file.

image4.gif

On the click event of the Write File Button, let's add the following lines of code for writing a file.

image5.gif

As you see in above code display, we are accessing the MyDocuments folder, which is a SpecialFolder. We cannot access the folder in normal mode, only trusted applications with elevated privilege can access such type of special fodlers. Then we are creating the file if there is some content in the txtWriteFile TextBox.

Now, on the click event of the Read File Button, let's add the lines of code to read the file.

image6.gif

As you see in the above code, we are checking whether the file Exists by using the Special Folder. Then we have simple StreamReader operations where we read file and display in the TextBox.

Let's install the application and run the out-of-browser mode application.

Now let's have some text and click on Write File.

image7.gif

Now if you browse through you're my Documents Folder, you can see the file, which is created with the text given as content.

image8.gif

That's write, let's check the content.

image9.gif

Yes, we have it. Now we can test the File Read operation.

image10.gif

That's it, we have successfully achieved File read and write from Local File System with Elevated trust level.

Hope this article helps.
 

Up Next
    Ebook Download
    View all
    Learn
    View all