File Tansfer in WCF Service
Posted by Sudhakar Kottapalli
category on 10/6/2009
for Intermediate level | Views : 18802
If you found plagiarised (copied)
or inappropriate content,
please let us know
the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
We have many options to transfer file from services. Previously in webservices have MTOM or use byte array with buffer to transfer files. But with WCF it is very easy to transfer file content in a stream format. This article will help you to create such service.
Data transfer is one of the common scenario while using services. But in most of the cases we use xml to transfer data in a string type. The same way if you want to transfer binary data you need to convert byte array to Base64 string and in the client side convert back this data to byte array. Below is the simple code to do that
byte myData = ...;
string cData = Convert.ToBase64String(myData);
But if we are using WCF Service there is much better way to do that which takes advantage of the channel that is used to communicate. Like NetTCPIP will allow binary data transfer directly and very quickly without encoding. Will discuss this in details about MTOM encoding using http binding in the below sections to transfer binary stream
To create this type of service we must be familiar with Message Contract. Let us create a simple Message Contract which will be used to carry our Binary Stream.
public class FileData
[MessageBodyMember(Order = 1)]
public Stream File;
Create a simple operation contract using this Message Contract
public interface IFileTranfer
void FileUpload(FileData value);
Actual implementation of service class is below
public class ServiceFileTranfer : IFileTranfer
public void FileUpload(FileData value)
//Access the stream here
StreamReader sr = new StreamReader(value.File);
Below is the configuration of the WCF Service. The most important is to define binding information. You must configure it to use MTOM to tranfer binary stream so set messageEncofing to Mtom and tansferMode to Streamed. Se the message and buffersize with the maximum stream size that is expected.
<binding name="HttpBinding_MTOM" messageEncoding="Mtom" transferMode="Streamed" maxBufferSize="65536" maxReceivedMessageSize="67108864">
<transport clientCredentialType="None" />
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="HttpBinding_MTOM"
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
There are many ways to implement such scenarios. But with WCF it can be done in an easy way and the performance will be dependent on the mode that is used. You can apply this scenario to basicHttpBinding, ws-* bindings.
About the Author