1. Problem
You want to allow the user to save a file anywhere on their system without the constraints of isolated storage.
2. Solution
Use the SaveFileDialog
object to persist a file to the user's file system from within a
user-initiated event handler, such as a button click or key press.
3. How It Works
Silverlight 3 introduced the new SaveFileDialog
object, which allows the user to select a file location that the
Silverlight application can save a file outside of isolated storage. Like the OpenFileDialog, the SaveFileDialog
must be raised in an event handler resulting from user interaction such
as a key press or button click. Once that's accomplished, using the SaveFileDialog is very straightforward.
Out-of-browser (OOB)
elevated trust applications have more access to the file system and are
not limited to isolated storage.
4. The Code
The code presents a simple UI with a button that the user can click to bring up the SaveFileDialog object (see Figure 1).
Just as with most any file-related dialog box, developers can configure the filter (e.g., .txt or .tiff) as well as the default file type. You are going to write out a simple text file, so you'll use Text Files (*.txt) has the source code that displays the SaveFileDialog object and writes out the file to the returned stream by calling the OpenFile() method.
Listing 1. Recipe 1. MainPage.xaml.cs File
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace Ch02_ProgrammingModel.Recipe2_14
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void btnSaveFile_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
sfd.FilterIndex = 1;
if (true == sfd.ShowDialog())
{
using (Stream fs = sfd.OpenFile())
{
byte[] textFileBytes = (new UTF8Encoding(true)).GetBytes(
"Welcome to Silverlight 4!!!! \r\n\r\nYour Authors,\r\n\r\nRob and Jit");
fs.Write(textFileBytes, 0, textFileBytes.Length);
fs.Close();
}
}
}
}
}