HowTo: Save a file from Silverlight using the SaveFileDialog
By rickvdbosch
- 2 minutes read - 250 wordsSaving a file from Silverlight using the SaveFileDialog, added in Silverlight 3, is easy. If you’re used to desktop development however, you might find yourself getting a SecurityException with the message ‘File operation not permitted. Access to path ‘xxx’ is denied.’. Here’s why:
In desktop development, you’re used to getting a filename from a SaveFileDialog. Next, you start doing whatever you need to be doing to the file, based on the filename. This would look something like this:
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == true)
{
StreamWriter streamWriter = new StreamWriter(saveFileDialog.SafeFileName);
streamWriter.Write("Follow me on twitter: @rickvdbosch");
streamWriter.Flush();
streamWriter.Close();
}
This results in the SecurityException. First time I saw the property, I genuinely thought it said SaveFileName. But, as you can see, it says SafeFileName. It is named safe, because the returned file name has all file path information removed for security purposes.
In Silverlight, if you want the above functionality, it should look something like this:
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == true)
{
StreamWriter streamWriter = new StreamWriter(saveFileDialog.OpenFile());
streamWriter.WriteLine("Follow me on twitter: @rickvdbosch");
streamWriter.Flush();
streamWriter.Close();
}
The OpenFile
method opens the file specified by the SafeFileName
returning a Stream
, giving you the opportunity to save whatever you want to save over there.
Hope this helps.
On a side note: the == true
part in the if condition is needed in this case. Because the ShowDialog method returns a nullable boolean it is not enough to use saveFileDiaolog.ShowDialog()
in the condition. Just so you know… 🙂