Monday, December 17, 2012

MVC3 and download files

I have come across several ways to have a web server allow files to be downloaded by clients. Some of these involve exposing a public method like this:
[WebMethod]
public void DownloadFile();

where the Response is populated with the bytes of the file contents.

But MVC makes it even easier with FileContentResult return type.

                if (System.IO.File.Exists(responseFile))
                {
                    using (var reader = new System.IO.StreamReader(file.FullName))
                        return new FileContentResult(System.IO.File.ReadAllBytes(file.FullName), "application");
                }

No comments:

Post a Comment