ASP.NET MVC Download Files

Download any file type from a controller in ASP.NET MVC using FileStreamResult.

// download a zip file as an attachment
public FileStreamResult DownloadZipFile()
{
	string path = Server.MapPath("/files/somefile.zip");
	if (System.IO.File.Exists(path))
	{
		Response.AppendHeader("content-disposition", "attachment;filename=somefile.zip");
		System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open); // don't use using keyword!
		return new FileStreamResult(stream, "application/x-zip-compressed"); // the constructor will fire Dispose() when done
	}
	else
		return null;
}
// download a jpeg as an attachment
public FileStreamResult DownloadJpegFile()
{
	string path = Server.MapPath("/files/someimage.jpg");
	if (System.IO.File.Exists(path))
	{
		Response.AppendHeader("content-disposition", "attachment;filename=someimage.jpg");
		System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open); // don't use using keyword!
		return new FileStreamResult(stream, "image/jpeg"); // the constructor will fire Dispose() when done
	}
	else
		return null;
}
// download a text file as an attachment
public FileStreamResult DownloadTextFile()
{
	string path = Server.MapPath("/files/somefile.txt");
	if (System.IO.File.Exists(path))
	{
		Response.AppendHeader("content-disposition", "attachment;filename=somefile.txt");
		System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open); // don't use using keyword!
		return new FileStreamResult(stream, "text/plain"); // the constructor will fire Dispose() when done
	}
	else
		return null;
}

Download any data type from a ASP.NET MVC controller using FileContentResult which takes a byte array.

public FileContentResult DownloadTextFile()
{
	byte[] bytes = System.Text.Encoding.ASCII.GetBytes("How now brown cow.");
	Response.AppendHeader("content-disposition", "attachment;filename=sometext.txt");
	return new FileContentResult(bytes, "text/plain");
}

Or use a FileStream to fill the byte array.

public FileContentResult DownloadTextFile()
{
	System.IO.FileStream stream = new System.IO.FileStream("somefile.txt", System.IO.FileMode.Open);
	byte[] bytes = new byte[stream.Length];
	stream.Read(bytes, 0, bytes.Length);
	Response.AppendHeader("content-disposition", "attachment;filename=somefile.txt");
	return new FileContentResult(bytes, "text/plain");
}