7

I have an asp.net mvc action that returns a file result. Behind the scenes, it's just returning a file from a directory. FilePathResult requires a content type, but I don't know that.

What is the proper way to return a file result if I only have the path to the file available?

Jim Geurts
  • 19,124
  • 23
  • 91
  • 105
  • Look at this http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature – Omar Mar 30 '10 at 04:13

2 Answers2

12

Take the file extension, and look it up in the registry. The entry for it will have a "Content type" property.

Here's a complete example of returning a FilePathResult from a controller action:

string filePysicalPath, fileName; //these need to be set to your values.

var reg = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey( Path.GetExtension( filename ).ToLower() );
string contentType = "application/unknown";

if ( reg != null )
{
    string registryContentType = reg.GetValue( "Content Type" ) as string;

    if ( !String.IsNullOrWhiteSpace( registryContentType ) )
    {
        contentType = registryContentType;
    }
}

return File( filePysicalPath, contentType, filename );
James Curran
  • 95,648
  • 35
  • 171
  • 253
  • @James Thanks! I was worried about performance implications of this but it seems like it's the only way. I'll just store the values in cache, I guess. – Jim Geurts Mar 30 '10 at 04:38
  • This doesn't help if the registry doesn't have a certain file extension in it. Most servers won't have the file extensions from Office products registered: ppt, pptx, doc, docx, etc. You can look in the registry, and if a Content Type is not found, just use "application/unknown". You can also just use that exclusively. I've never seen a bad result from using it. – Glazed Jan 08 '14 at 21:42
  • I edited the answer to include a complete example that defaults to "application/unknown". Even if the "Content Type" entry exists in the registry, it's not guaranteed to be non-empty, so that needs to be checked for, too. – Glazed Jan 08 '14 at 21:53
  • I've written a library that includes a MimeMap class that handles this for you, including caching the values. It reads from the registry and a Mime.Types file that comes from Apache. https://github.com/BizArk/BizArk3/wiki/BizArk.Core.Util.MimeMap – Brian Apr 17 '17 at 21:41
0

This approach won't hit the registry

    private FileResult CreateFileResult(byte[] file, string fileName)
    {
        var cd = new ContentDisposition
        {
            FileName = fileName,
            Inline = false
        };

        this.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
        return this.File(file, MediaTypeNames.Application.Octet);
    }
LawMan
  • 3,159
  • 24
  • 31