How to upload/Download file from wcf service

In this post, I will show you how to stream (upload and download) data through the WCF service.

  • Create a new website
  • Right-click on the website and add a new WCF service named FileStream.svc
  • Open the IFileStream.cs and add the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
[ServiceContract]
public interface IFileStream
{
    [OperationContract]
    string Upload(Stream inputStream);
    [OperationContract]
    Stream Download(string fileId);
    [OperationContract]
    string[] GetAvailableFiles();
}

Open FileStream.cs file and add the following code inside it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Web;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class FileStream : IFileStream
{
    private const string FILEPATH = @"C:\temp\download";
    private string GetDirectoryPath()
    {
    return FILEPATH;
    }
    public string Upload(System.IO.Stream inputStream)
    {
    string fileID = string.Format(@"{0}\{1}.txt", GetDirectoryPath(), Guid.NewGuid().ToString());
        StreamReader reader = new StreamReader(inputStream);
    string contents = reader.ReadToEnd();
        File.WriteAllText(fileID, contents);
    return fileID;
    }
    public System.IO.Stream Download(string fileId)
    {
        MemoryStream stream = new MemoryStream();
    byte[] buffer = File.ReadAllBytes(fileId);
        stream.Write(buffer, 0, buffer.Length);
        stream.Position = 0;
    return stream;
    }
    public string[] GetAvailableFiles()
    {
    return new DirectoryInfo(GetDirectoryPath()).GetFiles().Select(x => x.FullName).ToArray();
    }
}

Now, It’s time to configure the service. There is two way to configure the service. First through the code, and second through the config file. I will follow a later approach.Open web. config and go to the section and add the following code

<?xml version="1.0"?>
<configuration>
    <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.serviceModel>
    <services>
    <service behaviorConfiguration="streamServiceBehaviour" name="FileStream">
    <endpoint address="" binding="basicHttpBinding" contract="IFileStream" bindingConfiguration="streamBindingConfig"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
    </services>
    <behaviors>
    <serviceBehaviors>
    <behavior name="streamServiceBehaviour">
    <serviceDebug includeExceptionDetailInFaults="true"/>
    <serviceMetadata httpGetEnabled="true"/>
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <bindings>
    <basicHttpBinding>
    <binding name="streamBindingConfig" transferMode="Streamed">
    </binding>
    </basicHttpBinding>
    </bindings>
    </system.serviceModel>
</configuration>

In the above configuration, I have used basicHttpBinding and transferMode*is Streamed.

Let’s consume the service. Right-click on the project and add a new page and add the following code to it

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ServiceExample.aspx.cs" Inherits="ServiceExample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
    </div>
    <asp:Button ID="btnDownload" runat="server" onclick="btnDownload_Click" 
    Text="Download" />
    <asp:TextBox ID="TextBox1" runat="server" Height="235px" Width="377px"></asp:TextBox>
    </form>
</body>
</html>
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class ServiceExample : System.Web.UI.Page
{
    StreamService.FileStreamClient client = new StreamService.FileStreamClient();
    string fileId = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
 
     fileId=client.Upload(new MemoryStream(FileUpload1.FileBytes));
     Session["fileID"] = fileId;
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        Stream stream = client.Download((String)Session["fileID"]);
        StreamReader reader = new StreamReader(stream);
        TextBox1.Text = reader.ReadToEnd();
    }
}

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم