Skip to content

File Transfer with WCF: Part II

2009 October 2
tags: , ,
by stefanoricciardi

A few readers of my previous post on File Transfer with WCF have asked to share the implementation of the UploadFile and DownloadFile methods.

While I can’t share the complete implemention of the service for obvious Intellectual Property reasons, I will outline the basic steps involved in implementing the service. Please refer to my previous post for the details on the DataContracts and OperationContracts involved here.

NOTE: I have extracted these portions from the actual code. I cannot verify this to work as-is, but it should give you a head-start to complete your own service. You should also add your own error checking, and any pre or post-download and/or pre or post-upload processing as required by the business.

Download

public FileDownloadReturnMessage DownloadFile(FileDownloadMessage request)
{
    // parameters validation omitted for clarity
    string localFileName = request.MetaData.LocalFileName;

    try
    {
        string basePath = ConfigurationSettings.AppSettings["FileTransferPath"];
        string serverFileName = Path.Combine(basePath, request.MetaData.RemoteFileName);

        Stream fs = new FileStream(serverFileName, FileMode.Open);

        return new FileDownloadReturnMessage(new FileMetaData(localFileName, serverFileName), fs);
    }
    catch (IOException e)
    {
        throw new FaultException<IOException>(e);
    }
}

Upload

public void UploadFile(FileUploadMessage request)
{
    // parameters validation omitted for clarity
    try
    {
        string basePath = ConfigurationSettings.AppSettings["FileTransferPath"];
        string serverFileName = Path.Combine(basePath, request.MetaData.RemoteFileName);

        using (FileStream outfile = new FileStream(serverFileName, FileMode.Create))
        {
            const int bufferSize = 65536; // 64K

            Byte[] buffer = new Byte[bufferSize];
            int bytesRead = request.FileByteStream.Read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                outfile.Write(buffer, 0, bytesRead);
                bytesRead = request.FileByteStream.Read(buffer, 0, bufferSize);
            }
        }
    }
    catch (IOException e)
    {
        throw new FaultException<IOException>(e);
    }
}

Bookmark and Share

Technorati Tags: , , ,
No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS

8 visitors online now
8 guests, 0 members
Max visitors today: 8 at 12:47 am CEST
This month: 8 at 08-01-2010 12:47 am CEST
This year: 40 at 05-03-2010 04:48 am CEST
All time: 40 at 05-03-2010 04:48 am CEST