I have an 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?

Was it helpful?


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 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow