Returning a binary respose in ASP MVC RC3

In a previous post I showed how to return a binary file from a controller action, well, this no longer works in release candidate 3 of the framework. Instead you have to create a new ActionResult descendant to do the job for you. This is how I did it....

return new BinaryResult(data, Path.GetFileName(productFileName));


and the class is implemented like so:

public class BinaryResult : ActionResult
{
private string ClientFileName;
private byte[] Data;
private string VirtualFileName;

public BinaryResult(string virtualFileName, string clientFileName)
{
if (string.IsNullOrEmpty(virtualFileName))
throw new ArgumentNullException("VirtualFileName");
if (string.IsNullOrEmpty(clientFileName))
throw new ArgumentNullException("ClientFileName");

ClientFileName = clientFileName;
VirtualFileName = virtualFileName;
}

public BinaryResult(byte[] data, string clientFileName)
{
if (data == null)
throw new ArgumentNullException("Data");
if (string.IsNullOrEmpty(clientFileName))
throw new ArgumentNullException("ClientFileName");

ClientFileName = clientFileName;
Data = data;
}

public override void ExecuteResult(ControllerContext context)
{
if (!string.IsNullOrEmpty(VirtualFileName))
{
string localFileName = context.HttpContext.Server.MapPath(VirtualFileName);
FileStream fileStream = new FileStream(localFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
using (fileStream)
{
Data = new byte[fileStream.Length];
fileStream.Read(Data, 0, (int)fileStream.Length);
}//using fileStream
}

context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + ClientFileName);
context.HttpContext.Response.BinaryWrite(Data);
}
}

Comments

Popular posts from this blog

Connascence

Convert absolute path to relative path

Printing bitmaps using CPCL