File Transfer with WCF: Part II

1 minute read

This is the second post on a small series about transferring large files with WCF using streaming :

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);
    }
}

Updated:

Leave a Comment