Silverlight Open and Save Dialog Boxes

If you want your Silverlight app to be able to load and save data to the users file system in a location of their choice (such as My Documents, Desktop, etc.) you can use the SaveFileDialog and OpenFileDialog. This is different from reading and writing to Isolated Storage as it requires the user to interact with a dialog box, choose filename, etc. The user can also cancel out of the dialog box, which returns a value of false from the ShowDialog() method.

Below is a simple example of saving a hard-coded string "Test string to save." to a file as chosen by the user. In a live application you would want to think more carefully about possible problems arising from loading and saving, e.g. what if user loads a corrupt file, or a binary file where a text file was expected, etc. Also with the loading of files you should evaluate the security risks of allowing arbitrary data to be loaded into your application.

 

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Text Files (*.txt)|*.txt";
            dlg.DefaultExt = "*.txt";

            // if the user doesn't cancel           
            if (dlg.ShowDialog() == true)
            {
                try
                {
                    // create a StreamWriter over the base stream returned by SaveFileDialog's OpenFile() method
                    using (StreamWriter writer = new StreamWriter(dlg.OpenFile()))
                    {
                        writer.Write("Test string to save.");
                        writer.Close();
                    }
                }
                catch (Exception ex) // catch all, ideally you should catch specific exceptions in most-specific to general
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }



        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Text Files (*.txt)|*.txt";

            // if the user doesn't cancel
            if (dlg.ShowDialog() == true)
            {
                try
                {
                    string loadedText;
                    // create a StreamReader from OpenFileDialog's OpenText() method
                    using (StreamReader reader = dlg.File.OpenText())
                    {
                        loadedText = reader.ReadToEnd();
                        reader.Close();
                    }
                    MessageBox.Show(loadedText);
                }
                catch (Exception ex) // catch all, ideally you should catch specific exceptions in most-specific to general
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
 

SHARE:

Add comment

Loading