Click here to Skip to main content
15,122,379 members
Articles / Programming Languages / XML
Posted 9 Mar 2011

Tagged as


168 bookmarked

WCF Streaming: Upload/Download Files Over HTTP

Rate me:
Please Sign up or sign in to vote.
4.82/5 (59 votes)
9 Mar 2011CPOL3 min read
A sample for uploading/downloading large files from a browser to a WCF service via a web server.


Purpose of this article

I have tried to transfer large files over HTTP to/from WCF, but I have faced problems in that I was not able to upload files more than 45 KB in size. I have Googled over www, but I did not find any ready-to-use sample code/solution. Using the explanations over the www and MSDN, I have tried many configuration setting combinations and finally succeeded in transferring large files (I have tested up to 1GB on IE6).

I would like to share my experience so as to support efforts of others in this direction and to invite review comments from the developer community.


To transfer large files using “WCF service + HTTP”, we can use the following types of bindings:

  1. wsHttpBinding
  2. basicHttpBinding

In wsHttpBinding, we can set the transfermode attribute as Buffered, but there is a disadvantage in using this approach for large files, because it needs to put the entire file in memory before uploading/downloading, A large buffer is required on both the web client and the WCF service host. However, this approach is very useful for transferring small files, securely.

In basicHTTPBinding we can use the transfermode as Streamed so that the file can be transferred in the form of chunks. We have to ensure additional security mechanisms for transferring chunks. The security mechanisms are not explained in this posting.

Implementation: WCF Service

Create a new “WCF Service” project. Create a new service with the name TransferService. Now we will see an interface file “ITransferService” and a class file TransferService.cs. ITransferService should have two methods, one for upload and one for download.

WCF Service Sample Interface Code:
public interface ITransferService
    RemoteFileInfo DownloadFile(DownloadRequest request);
     void UploadFile(RemoteFileInfo request); 
public class DownloadRequest
    public string FileName;

public class RemoteFileInfo : IDisposable
    [MessageHeader(MustUnderstand = true)]
    public string FileName;

    [MessageHeader(MustUnderstand = true)]
    public long Length;

    [MessageBodyMember(Order = 1)]
    public System.IO.Stream FileByteStream;

    public void Dispose()
        if (FileByteStream != null)
            FileByteStream = null;
WCF Service Sample Interface Implementation Code:
public RemoteFileInfo DownloadFile(DownloadRequest request)
    RemoteFileInfo result = new RemoteFileInfo();
        string filePath = System.IO.Path.Combine(@"c:\Uploadfiles", request.FileName);
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); 

        // check if exists
        if (!fileInfo.Exists)
            throw new System.IO.FileNotFoundException("File not found", 

        // open stream
        System.IO.FileStream stream = new System.IO.FileStream(filePath, 
                  System.IO.FileMode.Open, System.IO.FileAccess.Read);

            // return result 
            result.FileName = request.FileName;
            result.Length = fileInfo.Length;
            result.FileByteStream = stream;
        catch (Exception ex)

        return result; 
    public void UploadFile(RemoteFileInfo request)
        FileStream targetStream = null;
        Stream sourceStream =  request.FileByteStream;

        string uploadFolder = @"C:\upload\";
        string filePath = Path.Combine(uploadFolder, request.FileName);

        using (targetStream = new FileStream(filePath, FileMode.Create, 
                              FileAccess.Write, FileShare.None))
            //read from the input stream in 65000 byte chunks
            const int bufferLen = 65000;
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                // save to output stream
                targetStream.Write(buffer, 0, count);


Settings of “Web.Config” in the WCF Service

The following settings are most important for transferring large data:

  • ReaderQuotas: We have to set the maximum sizes (this depends on our specific requirement). Here I have set to the maximum values where we can transfer data up to 2GB, as per MSDN/www documentation.
  • XML
    <binding name="TransferService"
           maxBufferSize="2147483647" transferMode="Streamed" >
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
         maxArrayLength="2147483647" maxBytesPerRead="2147483647" 

    A word about my experiences here: I have used the above settings alone and received the error “400 bad request” from the WCF service on the browser.

    This error may occur due to many reasons: the reasons might be configuration mismatch between the web server and the WCF service, or an exception raised in the WCF service etc.

  • BindingConfiguration: This attribute is not available by default in the endpoint section. When I added this attribute, the “400 bad request” exception disappeared and the upload and download executed well.
  • XML
    <endpoint address="" binding="basicHttpBinding" 
              contract ="ITransferService">

    Along with the above settings, HttpRuntime settings should also be placed in the web.config file as below:

    <httpRuntime maxRequestLength="2097151" //Maxvalue
         executionTimeout="14400"   />  //can be configured as per the requirement.

Implementation: Web Server

Create a new “web site” project. Place a link button and a file upload control on the web page. Create one more button to upload the file. Add the reference of the WCF service in “Service References” with a suitable name, currently FileTransferServiceReference.

The following changes need to be done in web.config after adding the service reference:

<binding name="BasicHttpBinding_ITransferService" closeTimeout="04:01:00"
     openTimeout="04:01:00" receiveTimeout="04:10:00" sendTimeout="04:01:00"
     allowCookies="false" bypassProxyOnLocal="false" 
     maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
     messageEncoding="Text" textEncoding="utf-8" 
  <readerQuotas maxDepth="128" 
      maxStringContentLength="2147483647" maxArrayLength="2147483647"
      maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
  <security mode="None">
      <transport clientCredentialType="None" 
              proxyCredentialType="None" realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />

Increase the values for the readerQuotas attribute and also increase the timeout settings.  

The code-behind of the page is the following:

protected void LinkButton1_Click(object sender, EventArgs e)
                    clientDownload = new TransferServiceClient();
        FileTransferServiceReference.DownloadRequest requestData = new DownloadRequest();

        FileTransferServiceReference.RemoteFileInfo fileInfo = new RemoteFileInfo();
        requestData.FileName = "";
        fileInfo = clientDownload.DownloadFile(requestData);

        Response.BufferOutput = false;   // to prevent buffering 
        byte[] buffer = new byte[6500];
        int bytesRead = 0;

        HttpContext.Current.Response.ContentType = "application/octet-stream";
                    "attachment; filename=" + requestData.FileName);

        bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);

        while (bytesRead > 0)
            // Verify that the client is connected.
            if (Response.IsClientConnected)

                Response.OutputStream.Write(buffer, 0, bytesRead);
                // Flush the data to the HTML output.

                buffer = new byte[6500];
                bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);
                bytesRead = -1;
    catch (Exception ex)
        // Trap the error, if any.
        System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);

protected void Button1_Click(object sender, EventArgs e)
    if (FileUpload1.HasFile)
        System.IO.FileInfo fileInfo = 
               new System.IO.FileInfo(FileUpload1.PostedFile.FileName);
        FileTransferServiceReference.ITransferService clientUpload = 
               new FileTransferServiceReference.TransferServiceClient();
               uploadRequestInfo = new RemoteFileInfo();

        using (System.IO.FileStream stream = 
               new System.IO.FileStream(FileUpload1.PostedFile.FileName, 
               System.IO.FileMode.Open, System.IO.FileAccess.Read))
            uploadRequestInfo.FileName = FileUpload1.FileName;
            uploadRequestInfo.Length = fileInfo.Length;
            uploadRequestInfo.FileByteStream = stream;

Now build both the IDE projects and execute the web server project. This still works only for less than 50KB! If you select a large file to be uploaded, you will see a blank webpage.

Now, you need to add one more attribute, MaxRequestLength, in the httpRuntime section in the system.web configuration file section, as below:

<httpRuntime maxRequestLength="2097150"/>

That is it! Now one can download and upload large files (I have tested up to ~1GB) from an IE6 browser over HTTP to a WCF service.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

India India
No Biography provided

Comments and Discussions

GeneralMy vote of 5 Pin
Member 781975218-Oct-19 12:27
MemberMember 781975218-Oct-19 12:27 
Questionwcf https ? Pin
kiquenet.com19-Mar-19 7:53
professionalkiquenet.com19-Mar-19 7:53 
QuestionThe Operation is not supported in the wcf test client because it uses type RemoteFileInfo Pin
Member 1315449428-Apr-17 6:55
MemberMember 1315449428-Apr-17 6:55 
QuestionGetting exceptionin Downloading a file when no file return(stream object is assigned) from service. error is An error occurred while receiving the HTTP response to http://localhost:53899/WebService.svc. This could be due to the service endpoint bindi Pin
Member 117611355-Aug-16 23:17
MemberMember 117611355-Aug-16 23:17 
AnswerRe: Getting exceptionin Downloading a file when no file return(stream object is assigned) from service. error is An error occurred while receiving the HTTP response to http://localhost:53899/WebService.svc. This could be due to the service endpoint b Pin
kiquenet.com20-Mar-19 3:23
professionalkiquenet.com20-Mar-19 3:23 
QuestionError Found in Upload Image File Pin
Divyesh Vadhavana9-Jun-16 23:54
MemberDivyesh Vadhavana9-Jun-16 23:54 
QuestionQuery : TransferServiceClient Pin
Member 1202799824-Feb-16 22:32
MemberMember 1202799824-Feb-16 22:32 
QuestionHow to call this webservice form classic asp Pin
Member 1171208215-Jun-15 6:28
MemberMember 1171208215-Jun-15 6:28 
QuestionIE11- "The whatever.pdf download was interrupted Pin
keslavi24-Sep-14 11:39
Memberkeslavi24-Sep-14 11:39 
AnswerRe: IE11- "The whatever.pdf download was interrupted Pin
Member 1130407810-Jul-15 4:04
MemberMember 1130407810-Jul-15 4:04 
BugMistake in your code Pin
Member 1102032827-Aug-14 7:12
MemberMember 1102032827-Aug-14 7:12 
GeneralRe: Mistake in your code Pin
Member 1149170811-Mar-15 4:48
MemberMember 1149170811-Mar-15 4:48 
QuestionFileInfo will not work in server Pin
eyedia13-Aug-14 5:47
Membereyedia13-Aug-14 5:47 
AnswerRe: FileInfo will not work in server Pin
Member 1102032827-Aug-14 7:21
MemberMember 1102032827-Aug-14 7:21 
QuestionUpload from Android and iOS Pin
Member 1071530420-May-14 1:04
MemberMember 1071530420-May-14 1:04 
QuestionThis isn't WCF, but hey concept is clear. thanks for sharing Pin
chetankumard2329-Apr-14 2:22
Memberchetankumard2329-Apr-14 2:22 
AnswerRe: This isn't WCF, but hey concept is clear. thanks for sharing Pin
Member 111826663-Mar-15 3:58
MemberMember 111826663-Mar-15 3:58 
GeneralRe: This isn't WCF, but hey concept is clear. thanks for sharing Pin
wcdeich41-Apr-15 8:31
Memberwcdeich41-Apr-15 8:31 
GeneralMy vote of 5 Pin
Mohammed Irfan27-Apr-14 19:37
MemberMohammed Irfan27-Apr-14 19:37 
GeneralMy vote of 1 Pin
Mohammed Irfan25-Apr-14 3:32
MemberMohammed Irfan25-Apr-14 3:32 
Question(400) Bad Request Error Pin
Member 445279122-Dec-13 22:40
MemberMember 445279122-Dec-13 22:40 
Questionbad request 400 error while uploading file larger than 64k Pin
Kalpesh Bhadra19-Dec-13 20:38
MemberKalpesh Bhadra19-Dec-13 20:38 
QuestionIt's Possible using in The Wndows Phone 8?? Pin
Member 96716403-Dec-13 5:01
MemberMember 96716403-Dec-13 5:01 
GeneralRe: It's Possible using in The Wndows Phone 8?? Pin
Wamuti29-Jan-14 9:41
MemberWamuti29-Jan-14 9:41 
BugHttp 400 Error : There might be a typing error in the address. Pin
Lokesh Kondapalli26-Oct-13 22:41
MemberLokesh Kondapalli26-Oct-13 22:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.