Cumartesi, Mart 08, 2008

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 tag which is widely used for uploading files in web page. Well, like HTML , OpenFileDialog could be used to build a file uploader quickly. Both must prompt user to select files. But unlike HTML , 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:

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())

//Eng: Store file content in 'text' variable
string text = reader.ReadToEnd();
}
}

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) {
//Eng: 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)) {

// Eng: 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;
}
}
}
}
}
}

Hiç yorum yok: