Dispose Returned stream in WCF

In this below method I have returned a file stream for downloading it in client or browser. Before returning that stream i have keep that file in a temporary location.After return that stream i have to dispose it and delete that directory.

public Stream DownloadAttachment()
Stream stream = null;
var directoryInformation = CommonServices.Utility.DirectoryHelper.GetTempFolderRootLocation();
string newFolderPath = "C:\\Attachments\\" + Guid.NewGuid();

string fullPath = newFolderPath + "\\" + fileName;
stream = File.OpenRead(fullPath);

catch (Exception exception)

return null;
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += (sender, args) =>
if (stream != null)
Directory.Delete(newFolderPath, true);
return stream;

Enjoy Coding…

2 thoughts on “Dispose Returned stream in WCF

  1. Thanks for sharing the info. Better unsubscribe the event handler.Else soon it will lead to memory leak and the server process will be recycled. It will affect the other services hosted in the same web application as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s