File Upload in Silverlight

Introduction

 
In this article, I will discuss how you can create your own File Upload feature in a Silverlight application.
 
Step 1
 
First, create a Silverlight Web application in Visual Studio 2008. You will see your default Page.xaml.
 
Step 2
 
On Create Page.xaml, change your code by adding the following Panel, Button, and TextBlock controls.
 
On the button click event handler, I write code to call the OpenFileDialog that allows us to browse files and gives us the selected file name. Here is the code. 
  1. public void Button_Click(object sender, RoutedEventArgs e) {  
  2.   OpenFileDialog dlg = new OpenFileDialog();  
  3.   dlg.Multiselect = false;  
  4.   dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png";  
  5.   bool ? retval = dlg.ShowDialog();  
  6.   if (retval != null && retval == true) {  
  7.     UploadFile(dlg.File.Name, dlg.File.OpenRead());  
  8.     StatusText.Text = dlg.File.Name;  
  9.   }  
  10.   else {  
  11.     StatusText.Text = "No file selected...";  
  12.   }  
As you can see from the above code, I call a method UploadFile by passing the selected file name from the OpenFileDialog.
 
The UploadFile method looks like the following. In this code, I use a WebClient class and a PushData method.
  1. private void UploadFile(string fileName, Stream data)  
  2.         {  
  3.             UriBuilder ub = new UriBuilder("http://localhost:3840/receiver.ashx");  
  4.             ub.Query = string.Format("filename={0}", fileName);  
  5.             WebClient c = new WebClient();  
  6.             c.OpenWriteCompleted += (sender, e) =>  
  7.             {  
  8.                 PushData(data, e.Result);  
  9.                 e.Result.Close();  
  10.                 data.Close();  
  11.             };  
  12.             c.OpenWriteAsync(ub.Uri);  
  13.         }  
  14.         private void PushData(Stream input, Stream output)  
  15.         {  
  16.             byte[] buffer = new byte[4096];  
  17.             int bytesRead;  
  18.             while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)  
  19.             {  
  20.                 output.Write(buffer, 0, bytesRead);  
  21.             }  
  22.         } 
Step 3
 
Add a new Generic Handler receiver.ashx.
 
Now let's add a class. Right-click on the project and add a new item by selecting Generic Handler in the right side templates as shown below.
 
filupload1
 
And add the following code on the code behind-
  1. <%@ WebHandler Language="C#" Class="receiver" %>  
  2.   
  3. using System;  
  4. using System.Web;  
  5. using System.IO;  
  6. public class receiver : IHttpHandler {  
  7.        public void ProcessRequest (HttpContext context) {  
  8.         string filename = context.Request.QueryString["filename"].ToString();  
  9.         using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))  
  10.         {  
  11.             SaveFile(context.Request.InputStream, fs);  
  12.         }  
  13.     }  
  14.     private void SaveFile(Stream stream, FileStream fs)  
  15.     {  
  16.         byte[] buffer = new byte[4096];  
  17.         int bytesRead;  
  18.         while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)  
  19.         {  
  20.             fs.Write(buffer, 0, bytesRead);  
  21.         }  
  22.     }  
  23.    
  24.     public bool IsReusable {  
  25.         get {  
  26.             return false;  
  27.         }  
  28.     }  
 
Step 4
 
Build and Run
 
That's all. You are done. Now just build and run your project. 
 
When you click the Select File button, you will see Browse files dialog that lets you browse the files.
 
filupload2
 
Note
 
You need to make sure your folder on the Web has to write permissions to upload files.
 

Summary

 
In this article, we learned about File Upload in Silverlight with an example.