SilverBullet, Silverlight

SilverBullet #8 – Accessing local files

silverbulletI’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.


Although the Silverlight security model prevents access to the local file system, it is very easy to open and save or import and export files to and from the file system. It is not possible to gain any information about the local file system, but the Silverlight framework can give you a stream to a file. Access is only granted if the dialogs are used from user-initiated code, like the Click event for example. If you try to show the dialog from other code, a SecurityException is thrown.


Opening a file uses the OpenFileDialog class, which lives in the System.Windows.Controls namespace. The OpenFileDialog class provides only one method, ShowDialog. This method shows a dialog that is modal to the browser, which means your application is locked for user input for as long as the dialog window is open. The method returns a bool indicating if one or more files are selected or not.

The OpenFileDialog class has a few properties:

  • Filter – a string to get or set the filter on which files are shown, for example “Excel (.xls)|*.xls|All Files (*.*)|*.*”
  • FilterIndex – an integer to get or set the index for the filter dropdown list
  • Multiselect – a bool to enable or disable the selection of multiple files
  • File – gets a FileInfo object for the selected file. If multiple files are selected, this is the first
  • Files – gets a collection of FileInfo objects that represents all selected files


Saving a file is pretty similar. Saving uses the SaveFileDialog class, which can be found in the System.Windows.Controls namespace too. Showing the dialog is done the same way as opening a file, using the ShowDialog method. When the user has selected a file or filename to save to, you can use the OpenFile method to get a stream to write the contents to. You should only call this method if showing the dialog returns True. If no file is selected when trying to open it, an InvalidOperationException is thrown.

The SaveFileDialog class has only four properties:

  • DefaultExt – a string to get or set the default extension
  • SafeFileName – a string to get the filename for the selected file
  • Filter – a string to get or set the filter on which files are shown
  • FilterIndex – an integer to get or set the index for the filter dropdown list


There’s an example demonstrating the OpenFileDialog class on MSDN, which shows a number of properties in practice. The example can be found here.

Shout it
Tags van Technorati: Silverlight
dotNed blogger
kick it on

Leave a Reply

Seo wordpress plugin by
%d bloggers like this: