Creating a File Upload Control that Works in the Sandbox

In HTML, it is easy to add file upload capabilities to your application using the INPUT element with type=”file”:

<input type="file" />

This renders a text box and a button, and when a user clicks on the button she is confronted with a file open dialog. She selects a file, and the text box gets populated with file name:

The input element is usually used inside of a form, and the contents of the file are sent to the form processing agent when the form is submitted.

WPF does not provide a file upload control out of the box, but it is very easy to construct your own using a TextBox, a Button, and Microsoft.Win32.OpenFileDialog. I have created a simple version of this control by deriving from UserControl. My UserControl has one public property, called File, which is of type Stream, and an event, called FileSelected, which is raised when the user chooses a new file using the OpenFileDialog.

The main logic for this control lives in the Click event handler for the Button:

        void SelectFile(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            bool? dialogResult = ofd.ShowDialog();

            if (dialogResult == true)
            {
                TBFileName.Text = ofd.SafeFileName;
                file = ofd.OpenFile();

                // raise the FileSelected event:
                OnFileSelected(EventArgs.Empty);
            }
        }

In order to make this work inside the sandbox for an Internet Zone XBAP, I need to populate the TextBox using the SafeFileName property on OpenFileDialog, rather than using the FileName property. FileName will provide the full path to the file, and hence is not safe to use in partial trust (you will get a SecurityException if you try to use it from an Internet Zone XBAP). SafeFileName gives you a sanitized file name – simply the name of the file, without disclosing the path. This may be used safely by a partial trust application.

If you have the July CTP installed, you can try out a little test XBAP that uses this control here. You can download source for the control and the test app here.

4 thoughts on “Creating a File Upload Control that Works in the Sandbox”

Comments are closed.