Geeks With Blogs
Peter Tweed Exploring and explaining the mysteries of .NET

Many business applications need the ability to open and save files from and to the user’s local computers.  With internet based applications the issues surrounding this are based on security and the rights the application receives to affect the user’s computer.

has the open and save file dialogs which enable the opening and saving of files to the user’s computer, while restricting the need for the application developer to need to know anything about the client environment.  This post will cover their simple and straightforward use and how to serialize and de-serialize data objects into and from those files using Silverlight’s support for JSON data serialization.  The code for this post can be found here.



1.    Create a Silverlight application.

2.    Add a reference to the System.Runtime.Serialization and System.ServiceModel.Web .NET assemblies.  System.Runtime.Serialization adds support for the DataContract and DataMember attributes that define what classes and properties of those classes can be serialized.  System.ServiceModel.Web adds support for JSON serialization using the DataContractJsonSerializer class.

3.    Add a class called Person and overwrite the class with the following code:


using System.Runtime.Serialization;


namespace OpenAndSave



    public class Person


        private string firstName;

        private string lastName;

        private string interestingFact;



        public string FirstName


            get { return firstName; }

            set { firstName = value; }




        public string LastName


            get { return lastName; }

            set { lastName = value; }




        public string InterestingFact


            get { return interestingFact; }

            set { interestingFact = value; }





4.    In the MainPage.xaml file add the following reference at in the UserControl xaml tag:




5.    In the MainPage.xaml file add the following xaml in the LayoutRoot grid:



            <ColumnDefinition Width="20%"></ColumnDefinition>

            <ColumnDefinition Width="*"></ColumnDefinition>

            <ColumnDefinition Width="20%"></ColumnDefinition>



            <RowDefinition Height="20%"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="50"></RowDefinition>

            <RowDefinition Height="50"></RowDefinition>

            <RowDefinition Height="50"></RowDefinition>

            <RowDefinition Height="50"></RowDefinition>

            <RowDefinition Height="20%"></RowDefinition>


        <data:DataGrid x:Name="PeopleDataGrid" Grid.Column="1" Grid.Row="1">


        <Button x:Name="AddButton" Content="Add A Person" Grid.Column="1" Grid.Row="2" Click="AddButton_Click"></Button>

        <Button x:Name="RemoveButton" Content="Remove A Person" Grid.Column="1" Grid.Row="3" Click="RemoveButton_Click"></Button>

        <Button x:Name="LoadButton" Content="Load A Person List" Grid.Column="1" Grid.Row="4" Click="LoadButton_Click"></Button>

        <Button x:Name="SaveButton" Content="Save Person List" Grid.Column="1" Grid.Row="5" Click="SaveButton_Click"></Button>


The above xaml defines layout of the grid, adds a datagrid and four buttons that will be used to add a person object to the datagrid, remove the selected person object from the datagrid, save the person objects currently in the datagrid to a file on the user’s computer and load person objects from a file on the user’s computer into the datagrid.


6.    In the MainPage.xaml.cs file add the following using statements to the top of the file:


using System.Collections.ObjectModel;

using System.Runtime.Serialization.Json;

using System.IO;


7.    In the MainPage.xaml.cs file replace the constructor with the following code:


        private ObservableCollection<Person> people = new ObservableCollection<Person>();


        public MainPage()



            this.Loaded += new RoutedEventHandler(MainPage_Loaded);



        void MainPage_Loaded(object sender, RoutedEventArgs e)


            PeopleDataGrid.ItemsSource = people;



        private void AddButton_Click(object sender, RoutedEventArgs e)


            people.Add(new Person());



        private void RemoveButton_Click(object sender, RoutedEventArgs e)


            if (PeopleDataGrid.SelectedItem != null)




In this code we define an ObservableCollection to hold the person objects and when the page is loaded we bind the collection to the datagrid.

When the add button is clicked we add a new person object to the collection.

When the remove button is clicked we remove the selected person object from the collection.


8.    Run the application.  You can now add and remove person objects to and from the datagrid:



OK.  We have done nothing with serialization or opening and saving files yet.  That’s next.


9.    Add the following code to the MainPage class in the MainPage.xaml.cs file:


        private void SaveButton_Click(object sender, RoutedEventArgs e)


            SaveFileDialog save = new SaveFileDialog();

            save.Filter = "Person Files (.SLJSONtxt)|*.SLJSONtxt|All Files (*.*)|*.*";

            save.FilterIndex = 1;


            bool? saveClicked = save.ShowDialog();

            if (saveClicked == true)


                System.IO.Stream stream = save.OpenFile();

                DataContractJsonSerializer ser = new DataContractJsonSerializer(people.GetType());

                ser.WriteObject(stream, people);





There are two things to go over in this code:


a.    The SaveFileDialog object is used to handle all the displaying and configuration of the save file window displayed to the user.  Notice the Filter property that defines the extension of the file we are going to display and save the file on disk with (‘.SLJSONtxt’).

b.    If the user clicks OK in the save file window the result is true.

c.    The OpenFile member of the SaveFileDialog object returns an IO stream for the file that has been created by the user entering the name and location of the file in the save file window that was displayed.

d.    Once we have the stream of the open file, we get to use the DataContractJsonSerializer to serialize the collection of person objects into the file stream.

e.    The stream is closed and the JSON format serialized data is written to the file and location specified by the user.


10. Run the app, add some records and click the save person list button.



11. Enter the location and name of the file (I used c:\ and test) and click save.

12. Using Notepad.exe open the file you saved (mine was c:\test.SLJSONtxt):



Note the information from the person objects in the datagrid was successfully serialized in JSON format into the file we specified through the save file window!


13. Add the following code to the MainPage class in the MainPage.xaml.cs file:


        private void LoadButton_Click(object sender, RoutedEventArgs e)


            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "Person Files (.SLJSONtxt)|*.SLJSONtxt|All Files (*.*)|*.*";

            open.FilterIndex = 1;


            open.Multiselect = false;


            bool? openClicked = open.ShowDialog();

            if (openClicked == true )


                Stream stream = open.File.OpenRead();

                DataContractJsonSerializer ser = new DataContractJsonSerializer(people.GetType());

                people = ser.ReadObject(stream) as ObservableCollection<Person>;


                PeopleDataGrid.ItemsSource = people;




You see that the use of the OpenFileDialog object is very similar to the use of the SaveFileDialog.

The primary difference is you use the OpenRead() member of the FileInfo object returned from the File property to open the IO stream of the file selected by the user.

Next the code de-serializes the stream object into the collection of persons using the DataContractSerializer object ReadObject method.  The deserialized collection of person objects are then bound to the datagrid.


14. Run the application, click the load a person list button and select the file we saved previously.





Congratulations!  You have implemented your own application to save and load data files.


 What have we done?


We have implemented our own custom serialize-able type.


We have implemented a user interface to manage a collection of objects of our type.


We have enabled the user to save a local copy of those objects in our own custom file type.


We have enabled the user to load a local copy of those objects from our own custom file type.


We have implemented JSON serialization and de-serialization of our custom type.



With very little coding we have taken advantage of Silverlight’s ability to allow users to open and save files and used Silverlight’s out of the box serialization capability for JSON.  These are common requirements of business applications for users to save a local copy of data and import it later into the application, once again showing Silverlight is a very easy technology to use to achieve such goals.

Posted on Friday, October 9, 2009 9:33 PM Silverlight | Back to top

Comments on this post: Silverlight - Opening and saving files

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © PeterTweed | Powered by: