Professional, Software

Safe File Open Dialog

Silverlight applications are sandboxed application that means they can not do anything that requires full trust such as reading the file on disk. This does not mean that Silverlight application can not read file on the disk at all but it means, user needs to allow it read certain file on the disk. This is achieved by Safe FileOpenDialog so that user can navigate the disk and pick the file he/she wants to make it available for the application. Even after this, application never gets the location of the file, it only gets the stream to the content of the file that it can use for things like showing in UI or uploading to webserver etc.

Here is a simple sample that just does that…

 The goal of this application is to read the txt file on the disk and show it in the TextBlock that is part of this application. As First step, create a new silverlight application and then Page.xaml looks like this…

<Canvas
        xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="parentCanvas"
        Loaded="Page_Loaded"
        x:Class="FileOpen.Page;assembly=ClientBin/FileOpen.dll"
        Width="640"
        Height="480"
        Background="White"
        xmlns:uicontrol="clr-namespace:Silverlight.Samples.Controls;assembly=ClientBin/Silverlight.Samples.Controls.dll">
  <TextBlock x:Name="txtFileContent" Width="557" Height="302" Canvas.Left="40" Canvas.Top="25" Text="TextBlock" TextWrapping="Wrap"/>
  <uicontrol:Button Click="OnClick" Text="Read File"/>
</Canvas>

I needed a UI control that launches the OpenFileDialog. Instead of building my own control, I just used the Button control that is part of Silverlight V1.1 Alpha SDK. This means I added the SilverlightUIControls project to my solution and I added it as a reference for my application.  

Code Behind for this file is pretty straight forward too…

using System;
using System.Windows.Controls;

namespace FileOpen
{
    public partial class Page : Canvas
    {
        public void Page_Loaded(object o, EventArgs e)
        {
            // Required to initialize variables
            InitializeComponent();
        }

        public void OnClick(object o, EventArgs e)
        {
            OpenFileDialog openfile = new OpenFileDialog();
            openfile.EnableMultipleSelection = false;
            openfile.Filter = "txt files (*.txt)|*.txt";
            openfile.ShowDialog();
            txtFileContent.Text = openfile.SelectedFile.OpenText().ReadToEnd();
        }
    }
}

Standard

5 thoughts on “Safe File Open Dialog

  1. Pingback: Recursive Reflection : Safe File Open Dialog

  2. Pingback: MSDN Blog Postings · Safe File Open Dialog

  3. I wanna ask you one thing…

    1. Is this the same as the way that we used in Windows Application??

    2. Is there any control like Folder Browser control from Window for Silverlight??

    Thanks in advance.

Leave a comment