web 2.0

News: Windows Phone 7 Phones Running Silverlight


Open File Dialog in Silverlight

Silverlight 2.0 Alpha introduced OpenFileDialog control which allows Silverlight applications to open and read *local* files outside Isolated Storage. It's better than the HTML <input> tag which is widely used for uploading files in web page. Well, like HTML <input>, OpenFileDialog could be used to build a file uploader quickly. Both must prompt user to select files. But unlike HTML <input>, OpenFileDialog control could be used to read and process the file data locally in Silverlight application. This is pretty powerful since Silverlight application will not need to upload the files to server for processing. What's more is that OpenFileDialog allows user to select multiple files at once. No need to create multiple instances of OpenFileDialog for that. Let's see some examples:

VB.NET Example 1: Open and read a single text file

Dim dlg As New Controls.OpenFileDialog
dlg.Filter = "Text Files (*.txt)|*.txt"
If dlg.ShowDialog = DialogResult.OK Then
    Using reader As IO.StreamReader = dlg.SelectedFile.OpenText
        'Store file content in 'text' variable
        Dim text As String = reader.ReadToEnd
    End Using
End If

C# Example 1: Open and read a single text file

OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
    using (StreamReader reader = dlg.SelectedFile.OpenText())
    
        // Store file content in 'text' variable
        string text = reader.ReadToEnd();
    }
}

VB.NET Examples 2:  Copy files to the application's isolated storage. 

Imports System.IO.IsolatedStorage
...
  
Dim dlg As New Controls.OpenFileDialog
dlg.Filter = "All files (*.*)|*.*"
dlg.EnableMultipleSelection = True
If dlg.ShowDialog = DialogResult.OK Then
    ' Save all selected files into application's isolated storage
    Dim iso As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
    For Each file As FileDialogFileInfo In dlg.SelectedFiles
        Using fileStream As IO.Stream = file.OpenRead
            Using isoStream As New _
                IsolatedStorageFileStream(file.Name, IO.FileMode.Create, iso)
 
                ' Read and write the data block by block until finish
                Do
                    Dim buffer(100000) As Byte
                    Dim count As Integer = fileStream.Read(buffer, 0, buffer.Length)
                    If count > 0 Then
                        isoStream.Write(buffer, 0, count)
                    Else
                        Exit Do
                    End If
                Loop
            End Using
        End Using
    Next
End If

C# Example 2: Copy files to the application's isolated storage. 

using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
...
  
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All files (*.*)|*.*";
dlg.EnableMultipleSelection = true;
if (dlg.ShowDialog() == DialogResult.OK) {
    // Save all selected files into application's isolated storage
    IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
    foreach (FileDialogFileInfo file in dlg.SelectedFiles) {
        using (Stream fileStream = file.OpenRead()) {
            using (IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(file.Name, FileMode.Create, iso)) {
 
                // Read and write the data block by block until finish
                while(true) {
                    byte[] buffer = new byte[100001];
                    int count = fileStream.Read(buffer, 0, buffer.Length);
                    if (count > 0) {
                        isoStream.Write(buffer, 0, count);
                    }
                    else {
                        break;
                    }
                }
            }
         }
    }
}

Tags:

Silverlight 1.1 | Silverlight 2.0 | Tutorial

Comments

rich , on 3/27/2008 8:14:42 AM Said:

rich

Hi,
When I try to use the OpenFileDialog in Silverlight 2, it does not show up as Modal window. Is it suppose to be? Appreciated if you could let me know what is your experience with it.
Thanks!

Alex , on 3/27/2008 12:05:33 PM Said:

Alex

1. Is it possible to read local files without user confirmation? I will have client application without user interaction and I would need this...
2. Is it possible to write some local files or modify them?
3. How many KB I can store in local storage?

Neo , on 3/28/2008 3:59:25 AM Said:

Neo

rich, it shows up as modal dialog window for me. The browser is locked, but music, animation, or music is still playing. The next code line is executed after the Open or Cancel button is clicked.

Neo , on 3/28/2008 4:07:00 AM Said:

Neo

@Alex

>>> 1. Is it possible to read local files without user confirmation? I will have client application without user interaction and I would need this...

No, Silverlight doesn't allow this for security reasons. This is to ensure that Silverlight application can never be harmful to client's computer. It's possible however to store data in Isolated Storage without user interaction.

>>> 2. Is it possible to write some local files or modify them?

No for now. I'm not sure if Silverlight team would develop SaveFileDialog or not.

>>> 3. How many KB I can store in local storage?

About 1 MB per Silverlight application (uniquely identified by domain and directory path), but in the future, users can configure to allow more space.

Florin , on 3/31/2008 4:45:55 AM Said:

Florin

Hi,

Is it possible to have the OpenFileDialog select only a directory and then use the Silverlight API to run through all files?

Also, another "good" thing would be to have the user select a location (a folder path) ONLY once, the application stores this location "somewhere" (most likely in the Isolated Storage) and the application will read the files in the folder later. Also the user should not do this selection each time he/she runs the application. I know it runs into a security issue, but is it addressed in any way?

Thanks!

gridrunner , on 4/6/2008 11:51:50 AM Said:

gridrunner

Hey there,

"System.Windows.Controls.FileDialogFileInfo" elements do contain the filename, but not the path.
Thus it seems impossible to -for example- write a real world-usable file upload component. What a pity!

I didn't try if .ReadFile works with the actual filepath, but even if it does, how are we supposed to show the user which files they actually selected (given that multiple files each having the same filename may exist within multiple folders) ?

I wonder if the path is omitted from .Name for security reasons. If so, I don't like this at all. It's just like having a firewall that blocks Port 25 TCP ("because our policy says so!") when you are supposed to run an SMTP server behind that thing. Just plain contra productive.

Neo , on 4/7/2008 2:53:35 PM Said:

Neo

@Florin,

>>> Is it possible to have the OpenFileDialog select only a directory and then use the Silverlight API to run through all files?

OpenFileDialog doesn't support selecting a folder. It can however allow users to select multiple files in a folder. Set 'OpenFileDialog.EnableMultipleSelection = True' before showing the dialog. After user select the files, you can enumerate through all the files in the 'OpenFileDialog.SelectedFiles'.


>>> Also, another "good" thing would be to have the user select a location (a folder path) ONLY once, the application stores this location "somewhere" (most likely in the Isolated Storage) and the application will read the files in the folder later.

Ok, imagine yourself as a user. You visit a website that automatically runs a Silverlight application. Before you know it, the application has copied your private files and upload them without your knowledge. Of course, you might have forgot that last week or so, the application asked you to select a directory, and you as an ordinary PC user didn't know the application would be able to steal your files later on.

This is what SL is designed to protect, your private files. This is to ensure that SL application won't steal them without your knowledge.


@gridrunner

>>> "System.Windows.Controls.FileDialogFileInfo" elements do contain the filename, but not the path.

Because the path might contain sensitive information like Name, User Name, Password, etc. Consider this "C:\Users\Michael Jackson\Documents\sexy-children-pics\lindaATgmail.com\1.jpg". Why does a Silverlight application wants to know the path for?

I think you are a bit harsh on Silverlight here. It is not just Silverlight that shows only the file names. Html controls, Flash and Java do not show the full path either. And, full-featured upload controls have been built already.

hefei , on 4/11/2008 12:14:20 AM Said:

hefei

I try it!

John , on 5/29/2008 1:53:14 AM Said:

John

>>> Is it possible to have the OpenFileDialog select only a directory and then use the Silverlight API to run through all files?

This feature is good idea if system confirmation (non disableable) dialog was displayed.

Willy Achmat , on 7/7/2008 7:46:01 PM Said:

Willy Achmat

Thanks, helpfull

Mina , on 8/17/2008 5:20:49 AM Said:

Mina

I have a silverlight 2.0 player, I wanted to use the OpenFileDialog to know which video file to open so I need the name and the path of the file to open it. Is there a way to do that?
Thanks

busby seo test , on 1/12/2009 4:17:45 PM Said:

busby seo test

thank you for the information.

çağlar , on 3/3/2009 9:23:21 AM Said:

çağlar

Is there anymore reference ?
Im taking errors: dlg.EnableMultipleSelection, dlg.SelectedFiles

Perfect Home Design , on 3/12/2009 10:11:45 AM Said:

Perfect Home Design

everything is fine to me for using the silverlight

all funny sayings , on 3/12/2009 8:10:20 PM Said:

all funny sayings


I’m really impressed with your article, such great information you mentioned here, thanks for your sharing and waiting to see your future posts.

Carlos , on 3/24/2009 6:50:47 AM Said:

Carlos

ARe there any examples of these uses. I keep running into the code examples but I would like a live working example.

Simulation pret , on 6/16/2009 2:52:18 PM Said:

Simulation pret

Thank you very much for this great tutorial. It will definitely be very helpful to me.

franchises for sale , on 6/19/2009 10:52:57 AM Said:

franchises for sale

hmmmm i'm hungry.  Ooops, focus matthew focus matthew focus.   Just browsing, thinking of food and browsing.  Post some more Smile MunchMunch

vishal , on 6/20/2009 3:09:19 AM Said:

vishal

i got an error while uploading a file saying that
Dialogs must be user-initiated.

SEO 対策 沖縄 ホームページ制作 , on 6/22/2009 9:11:47 PM Said:

SEO 対策 沖縄 ホームページ制作

nice tutorial. thanks for the posting.

win at slot machines , on 7/29/2009 7:21:15 PM Said:

win at slot machines

Just a quick note – I didn’t want anyone to think that I’d given up on Silver light 3 or that these posts.

movers , on 8/5/2009 6:14:14 AM Said:

movers

who said that?

Best weight loss pills , on 8/5/2009 3:41:58 PM Said:

Best weight loss pills

I am a wannabe web programming and right now i am collecting resources i can use to make one. It seems Silverlight a nice application to use. Thank you for sharing the codes.     

Dloadmp3 , on 8/6/2009 5:41:02 AM Said:

Dloadmp3

The best article I've read today Smile Thanks!

Partenaires , on 8/9/2009 5:09:29 PM Said:

Partenaires

Great article. I definitely didn't know how to do that.

Los Angeles , on 8/17/2009 1:12:01 AM Said:

Los Angeles

Thanks for your awesome coding. It really makes me happy.

pest control las vegas , on 8/19/2009 12:39:07 AM Said:

pest control las vegas

Great article. I definitely didn't know how to do that.

Sabrina , on 8/20/2009 8:03:04 PM Said:

Sabrina

Thanks for the nice code. It works pretty well. Smile

Guitar Wallpaper , on 8/23/2009 5:24:26 PM Said:

Guitar Wallpaper

You have a nice info..
THank's for share..Smile

Todd Morrison , on 8/26/2009 7:07:43 AM Said:

Todd Morrison

jesus, am i the only person that noticed the michael jackson joke?!

Zotrim , on 8/30/2009 1:38:49 PM Said:

Zotrim

I used to know Visual Basic quite well but I have not got into Silverlight at all. Too busy I suppose.

sts , on 9/5/2009 10:28:12 PM Said:

sts

Very informative site, i must bookmark it, keep posting interesting articles...

wines , on 9/6/2009 8:35:18 AM Said:

wines

interesting article and i have bookmarked for further reference.

Weird Stories , on 9/12/2009 8:25:00 PM Said:

Weird Stories

Thanks for the update... Smile

агенство переводов , on 9/18/2009 1:44:54 AM Said:

агенство переводов

Your post is great and blog is just awesome.

best electric toothbrush , on 9/24/2009 6:24:57 AM Said:

best electric toothbrush

Good information, I'll bookmark the site

sher , on 9/25/2009 6:03:10 AM Said:

sher

hey was just wondering..is it possible to have a scenario where there is an open file dialog that allows the user to select the file they want, attach it to an email and send it?

acai berry benefits , on 9/25/2009 10:29:23 PM Said:

acai berry benefits

Very good and informative article,thank you!

Narconon , on 9/30/2009 10:07:05 AM Said:

Narconon

thank you very much for your insightful post. it was very interesting. Laughing

Life Insurance , on 10/5/2009 2:52:15 AM Said:

Life Insurance

What is Microsoft Silverlight & how its work ?

SEO , on 10/5/2009 2:52:44 AM Said:

SEO

What is 'Silverlight'? I have downloaded it from MSN, but don't know what are its usage and how it is used.?

cheap microwave , on 10/6/2009 4:55:24 AM Said:

cheap microwave

I didnt get the michael joke either :-(

remote shock collar , on 10/6/2009 8:39:06 AM Said:

remote shock collar

I need help too, what is it exactly??

best toaster , on 10/7/2009 3:06:32 AM Said:

best toaster

Great info thanks

black kitchen cabinets , on 10/12/2009 6:06:29 AM Said:

black kitchen cabinets

thanks for sharing. Smile

anne of green gables dvd , on 10/13/2009 1:38:32 PM Said:

anne of green gables dvd

Thanks, I love Silverlight

payday loans canada , on 10/14/2009 7:48:23 AM Said:

payday loans canada

I recently came across your blog and have been reading. I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Cosmetic dentists Palm beach , on 10/17/2009 5:41:22 PM Said:

Cosmetic dentists Palm beach

I learned alot from this article. It's better than the HTML <input> tag which is widely used for uploading files in web page. Well, like HTML , Open File Dialog could be used to build a file uploader quickly. Both must prompt user to select files.

Home loan , on 10/19/2009 10:00:16 PM Said:

Home loan


Admiring the time and effort you put into your blog and detailed information you offer!

unlock iphone , on 10/23/2009 8:28:47 PM Said:

unlock iphone

Thanks for the helpful tips. I liked the detail description of coding. Open file-dialog seems pretty nice.

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading