Silverlight does not have direct access to the local file system for security reasons. However, you can still prompt the user to select a specific file to open using the OpenFileDialog similarly to how you do in .NET. Here’s some basic code that demonstrates opening a user specified file using Silverlight 2 Beta 1.

This basic example opens up a user specified file, and displays its contents within a textbox.

Page.xaml file

Page.xaml.cs file


using System.Windows;
 using System.Windows.Controls;
 using System.IO;

namespace SilverlightOpenFileTest
 {
     public partial class Page : UserControl
     {
         public Page()
         {
             InitializeComponent();
         }

        private void btnSelectFile_Click(object sender, RoutedEventArgs e)
         {
             OpenFileDialog fileDialog = new OpenFileDialog();

            // Show the Open File Dialog
             DialogResult result = fileDialog.ShowDialog();

            // Open the file if OK was clicked in the dialog
             if (result == DialogResult.OK)
             {
                 FileDialogFileInfo fi = fileDialog.SelectedFile;
                 Stream s = fi.OpenRead();
                 StreamReader reader = new StreamReader(s);
                 txtFile.Text = reader.ReadToEnd();
             }
         }
     }
 }

Now isn’t that simple? I wonder if they’ll ever add the SaveFileDialog…