File Upload from Silverlight using WCF

Objective

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 WCF

  1. Create  WCF Service
  2. Consume in SilverLight client

Follow the Steps below

Step 1

Create and Host the WCF Service.

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

    using System;

    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    namespace FileUploadService
    {
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            void SaveFile(UploadFile UploadFile);
    }
    }

  3. 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.
  4. [DataContract]

    public class UploadFile

            {
                [DataMember]
                public string FileName;
                [DataMember]
                public byte[] File;
            }

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

Service1.svc.cs

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);
FileStream.Close();
FileStream.Dispose();
}
}
} 

Web.Config


<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<bindings>
<basicHttpBinding>
<binding name="ServicesBinding"
              maxReceivedMessageSize="2000000"
              maxBufferSize="2000000">
<readerQuotas
            maxArrayLength="2000000"
            maxStringContentLength="2000000"/>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="FileUploadService.Service1" behaviorConfiguration="FileUploadService.Service1Behavior">
<endpoint address="" binding="basicHttpBinding" contract="FileUploadService.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="FileUploadService.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel> 

Step 2 : Create the Silver Light Client and consume the service

on button click event , open file dialog will allow user to select the file to be uploaded.  and then content of file will get converted in byte array and then we will call the WCF service.

MainPage.xaml.cs

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()
        {
            InitializeComponent();
            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);
                strm.Dispose();
                strm.Close();
                UploadFile file = new UploadFile();
                file.FileName = fileDialog.File.Name;
                file.File = Buffer;

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

            }

            else
            {
                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";
        }

}
}