Upload or Get a File Using ASP.Net WCF Service on Server

In this article we will learn how to upload or get a file using an ASP.Net WCF Service on the server.

The scenario is that if I have one internal domain server and one DMZ machine hosted in the cloud and for some reason we upload the file then we need to save the file on the internal server.

Now let us see how ot use WCF to save the file on the internal server.

Step 1

Create a WCF project in Visual Studio.

Now open the IServices class and add the following operation contract.

  1. [OperationContract]  
  2. bool UploadToTempFolder(byte[] pFileBytes, string pFileName);  
  3.   
  4. [OperationContract]  
  5. byte[] GetFileFromFolder(string pFileName);  
Step 2

Open the Services.svc class and the following code.

This method is used to save the file on the server.
  1. public bool UploadToTempFolder(byte[] pFileBytes, string pFileName)   
  2. {  
  3.     bool isSuccess = false;  
  4.     FileStream fileStream = null;  
  5.     //Get the file upload path store in web services web.config file.  
  6.     string strTempFolderPath = System.Configuration.ConfigurationManager.AppSettings.Get("FileUploadPath");  
  7.     try {  
  8.   
  9.         if (!string.IsNullOrEmpty(strTempFolderPath))   
  10.         {  
  11.             if (!string.IsNullOrEmpty(pFileName))   
  12.             {  
  13.                 string strFileFullPath = strTempFolderPath + pFileName;  
  14.                 fileStream = new FileStream(strFileFullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);  
  15.                 // write file stream into the specified file  
  16.                 using(System.IO.FileStream fs = fileStream)   
  17.                 {  
  18.                     fs.Write(pFileBytes, 0, pFileBytes.Length);  
  19.                     isSuccess = true;  
  20.                 }  
  21.             }  
  22.         }  
  23.     } catch (Exception ex)   
  24.     {  
  25.   
  26.         throw ex;  
  27.   
  28.     }  
  29.   
  30.     return isSuccess;  
  31. }  
  32.   
  33. This method will give you the file content as a byte.  
  34.   
  35. public byte[] GetFileFromFolder(string filename)   
  36. {  
  37.     byte[] filedetails = new byte[0];  
  38.     string strTempFolderPath = System.Configuration.ConfigurationManager.AppSettings.Get("FileUploadPath");  
  39.     if (File.Exists(strTempFolderPath + filename)) {  
  40.         return File.ReadAllBytes(strTempFolderPath + filename);  
  41.     } else return filedetails;  
  42. }  
Now our service is created and we will create the web application to consume the service and save the file.

Step 3

Create an empty website from Visual Studio.

Add one file upload control and one button to upload the file.
  1. <table>  
  2.     <tr>  
  3.         <td>  
  4.             <span>Select File : </span>  
  5.         </td>  
  6.         <td>  
  7.             <asp:FileUpload ID="FileUpload1" runat="server" />  
  8.         </td>  
  9.     </tr>  
  10.     <tr>  
  11.         <td colspan="2">  
  12.             <asp:Button runat="server" ID="btnUpload" Text="Upload File" OnClick="btnUpload_Click" />  
  13.         </td>  
  14.     </tr>  
  15.     <tr>  
  16.         <td>  
  17.             <span>File Upload Starts on :</span>  
  18.         </td>  
  19.         <td>  
  20.             <asp:Label runat="server" ID="lblTimeStarts"></asp:Label>  
  21.         </td>  
  22.     </tr>  
  23.     <tr>  
  24.         <td colspan="2">  
  25.             <asp:Button runat="server" ID="btnGetUploadedFile" OnClick="btnGetUploadedFile_Click" Text="Get Uploaded File" />  
  26.             <br />  
  27.             <asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">  
  28.                 <ItemTemplate>  
  29.                     <asp:LinkButton ID="LinkButton1" runat="server" CommandName="GetFile" Text="  
  30.                         <%# (string)Container.DataItem %>/>  
  31.                     </ItemTemplate>  
  32.                 </asp:DataList>  
  33.             </td>  
  34.         </tr>  
  35.   </table>  
Add the service to the website. To do this right-click on the website and click on add web reference.

After adding the web reference add the following code to the button event.
  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2.     {  
  3. //Check file is selected or not  
  4.         if(FileUpload1.HasFile)  
  5.         {  
  6.         System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();  
  7.         timer.Start();  
  8.         //To Service  
  9.         #region Upload Files  
  10.   
  11.         string filename = FileUpload1.FileName;  
  12.         byte[] filebyte = FileUpload1.FileBytes;  
  13.   
  14. //Service refrence          
  15. FileUploadWCF.ServiceClient objAttachment = new FileUploadWCF.ServiceClient();  
  16.           
  17. //pass the file byte to service  
  18.         objAttachment.UploadToTempFolder(filebyte, filename);  
  19.         #endregion  
  20.         timer.Stop();  
  21.         lblTimeStarts.Text = "File upload takes >>>" + Convert.ToString((TimeSpan.FromMilliseconds(timer.ElapsedMilliseconds).Milliseconds)) + " milliseconds. <br>";  
  22.   
  23.         writetheFileNameInText(filename,"output");  
  24.         bindUploadFile(DataList1, "output");  
  25.               
  26.     }  
  27.     }  
  28. private void writetheFileNameInText(string fileName,string outputFileName)  
  29.     {  
  30.   
  31.         using (StreamWriter w = File.AppendText(Server.MapPath(@"~\App_Data\" + outputFileName + ".txt")))  
  32.         {  
  33.             w.WriteLine(fileName);  
  34.         }  
  35.     }  
  36.   private void bindUploadFile(DataList dl,string outputFileName)  
  37.     {  
  38.         List<string> lstfileName = new List<string>();  
  39.         lstfileName = gettheFileNamefromText(outputFileName);  
  40.   
  41.         dl.DataSource = lstfileName;  
  42.         dl.DataBind();  
  43.       
  44.     }  
Now execute the code and you will see the following screen.

Upload

After uploading the file it will show the files just below the Get Uploaded File.

Now this is in the development mode. If we host the service on IIS then we need to change the WCF binding depending on the requirements.

Please find the attached source code for WCF services and Temp web site.