File Transfer with WCF: Part III

1 minute read

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

I am closing this series of posts by sharing a skeleton for the client side handling of the uploaded and downloaded files. Please note that the following are excerpt from a larger context and so will not compile in your environment as is: they are only intended to give a rough idea of how the files can be handled.

Download

private void IssueDownloadRequest(string localFile, string serviceUrl, FileDownloadMessage request)
{
this.service = this.proxy.OpenProxy(serviceUrl);

try
{
using (FileDownloadReturnMessage response = this.service.DownloadFile(request))
{
if (response != null && response.FileByteStream != null)
{
SaveFile(response.FileByteStream, localFile);
}
}

this.proxy.CloseProxy(this.service);
}
catch (Exception e)
{
throw new FileTransferProxyException("Error while downloading the file", e);
}
finally
{
// we expect the stream returned from the server to be closed by the
// server itself so nothing to be done with it here. Just abort
// the proxy if needed.
this.proxy.AbortProxyIfNeeded(this.service);
}
}

private static void SaveFile(Stream saveFile, string localFilePath)
{
const int bufferSize = 65536; // 64K

using (FileStream outfile = new FileStream(localFilePath, FileMode.Create))
{
byte[] buffer = new byte[bufferSize];
int bytesRead = saveFile.Read(buffer, 0, bufferSize);

while (bytesRead > 0)
{
outfile.Write(buffer, 0, bytesRead);
bytesRead = saveFile.Read(buffer, 0, bufferSize);
}
}
}

Upload

public void UploadFile(string localFileName, string serviceUrl, FileTypeEnum fileType)
{
this.service = this.proxy.OpenProxy(serviceUrl);
try
{
using (Stream fileStream = new FileStream(localFileName, FileMode.Open, FileAccess.Read))
{
var request = new FileUploadMessage();
string remoteFileName = null;
if (fileType == FileTypeEnum.Generic)
{
// we are using the service as a "FTP on WCF"
// give the remote file the same name as the local one
remoteFileName = Path.GetFileName(localFileName);
}

var fileMetadata = new FileMetaData(localFileName, remoteFileName, fileType);
request.MetaData = fileMetadata;
request.FileByteStream = fileStream;

this.service.UploadFile(request);
this.proxy.CloseProxy(this.service);
}
}
catch (IOException)
{
throw new FileTransferProxyException("Unable to open the file to upload");
}
catch (Exception e)
{
throw new FileTransferProxyException(e.Message);
}
finally
{
this.proxy.AbortProxyIfNeeded(this.service);
}
}

Updated:

Leave a Comment