File Upload in Silverlight using WCF

No.of Views3487
Bookmarked0 times
By  Dhananjay Kumar   On  02 Oct 2010 09:10:29
Tag : Silver Light and XAML , Files and Folders
This article will explain, How to upload a file from Silver Light client to server location using WCF.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at



This article will explain, How to upload a file from SilverLight client to server location using WCF.To achieve above task, follow the below steps. I am assuming here, that Reader has a basic concept of

1.    WCF
2.    Silver Light
3.    Cross Domain Issue
4.    Hosting of  WCF Service

For details on these topics, you could find astronomical number of articles on the Web. To Read articles written by me on above topic please Click Here

Pictorial representation of output

Image Loading


Image Loading


Image Loading

Follow the Steps below

Step 1

Create and Host the WCF Service.

a.    Create the Contract. This got only one method, which is taking as input a file to upload.


Image Loading

b.    Create the Data Contract. This is going to contain the information about the uploaded file.  You could either put this UploadFile Data Contract in same file with contract or in separate file.

[DataContract]public class UploadFile
        [DataMember]public string FileName;

        [DataMember]public byte[] File;

 c.    Implement the Service. We are simply creating instance of FileStream  in create mode and writing the stream into that. 

Image Loading


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Configuration;
using System.Web;
using System.ServiceModel.Activation;
using System.IO;

namespace FileUploadService
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]public class Service1 : IService1
    {public void SaveFile(UploadFile UploadFile)
  FileStream FileStream = new FileStream("E:\\FileUpload\\" + UploadFile.FileName, FileMode.Create);
            FileStream.Write(UploadFile.File, 0, UploadFile.File.Length);



 d.    Modify the Web.Config. Binding to be used is basicHttpBinding. I am setting the Buffer size and max Message received size also here.


    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        <binding name="ServicesBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
          <readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
      <service name="FileUploadService.Service1" behaviorConfiguration="FileUploadService.Service1Behavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="basicHttpBinding" contract="FileUploadService.IService1">
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
            <dns value="localhost"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <behavior name="FileUploadService.Service1Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>

e.     Host the service in IIS. Make sure you have put the access policy file at root directory of the server. If you have not done this, you will be getting cross domain error while accessing the service in Silver Light client.  After hosting in IIS, browse the service to make sure, service is running and hosted properly.For details of Cross domain issue read my article

By competing of Step 1, we have successfully created and hosted our service in IIS.

Step 2

Create the Silver Light Client and consume the service

In belnd , I have just created one button and one text box. On clicking of the Button File Open Dialog Box will get open and user will select the file to uplaod. Text box is used to display the message thet whether file is successfully saved at server or not.  If you don’t want to use Blend no issue. Just create a simple Silver Light application and add one button and text box on that. 

Image Loading

Generated XAML code is as below.

    xmlns:d="" xmlns:mc="" x:Class="FileUpload.MainPage" 
    Width="Auto" Height="Auto" mc:Ignorable="d">
    <Grid x:Name="LayoutRoot" Background="#FF241515" Margin="-0.05,0.044,-14.05,-15.956" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" Width="420" Height="320">

    		<RowDefinition Height="0.48*"/>
    		<RowDefinition Height="0.52*"/>
    			<RotateTransform Angle="0.359"/>
    	<Button Margin="10,10,10,10" Background="#FF1688E9" BorderThickness="2,2,2,2" FontSize="18" FontWeight="Bold" Content="Click To Upload the File to Server" Click="Button_Click"/>
    	<TextBox x:Name="txtFileDisplayName" Margin="32.191,37.471,44.252,41.08" Grid.Row="1" Text="" TextWrapping="Wrap" Foreground="#FFA32929" BorderThickness="3,3,3,3" FontWeight="Bold" FontFamily="Arial Rounded MT Bold" FontSize="18"/>


Step 3

Add the Service Reference

To add the Service Reference in the Silver Light, right click on the Service and add Service reference.

Step 4

Write the code behind


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.IO;
using FileUpload.ServiceReference1;
using System.Windows.Browser;

namespace FileUpload
{public partial class MainPage : UserControl
    {public OpenFileDialog fileDialog = null;
        Service1Client proxy = null;public MainPage()
            proxy = new Service1Client();
        }private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
            fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Filter = "All Files|*.*";bool? retval = fileDialog.ShowDialog();if (retval != null && retval == true)

              Stream strm = fileDialog.File.OpenRead();byte[] Buffer = new byte[strm.Length];
                strm.Read(Buffer, 0, (int)strm.Length);
                UploadFile file = new UploadFile();
                file.FileName = fileDialog.File.Name;
                file.File = Buffer;

                proxy.SaveFileCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_SaveFileCompleted);

                txtFileDisplayName.Text = " No File Selected ";
        }void proxy_SaveFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {if (e.Error == null)
                txtFileDisplayName.Text = fileDialog.File.Name + "Successfully Saved at ServerLocation"; 

 Explanation of code

1.    We are here reading the file and converting content of the file in form of stream. 

Image Loading

2.    We are creating instance of FileDialog to show file dialog to user and then select the file to be saved.  Multi select is set to false.  It means user can not select more than one file at one time. 

Image Loading

3.    We are calling the Save File operation of service asynchronously on the proxy instance. Proxy is instance of the Service class.

Image Loading

4.    We are creating instance of Data Contract and assigning property values by reading the file name through FileOpenDialog and stream by converted stream 

Image Loading

Step 4

Press F5 to run the application
Thank you very much for reading this article. I hope, it would have helped you out. Happy Coding.

Sign Up to vote for this article
About Author
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Joined date-20 Jul 2009
Home Page-
Blog Page-
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at . You can follow him and reach him at
Other popularSectionarticles
There is no comments for this articles.
Leave a Reply
Display Name:
(not display in page for the security purphase)
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top