I am trying to determine dynamically the content/type of a input file. If I would be in a windows application I could write code like this (from this blog)
private string GetContentType(string fileName) {
string contentType = "application/octetstream";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (registryKey != null && registryKey.GetValue("Content Type") != null)
contentType = registryKey.GetValue("Content Type").ToString();
return contentType;
}
What other methods are more suitable for an MVC application?
I would like to use the param within the Controller.File(...) method that receive a filepath and a contentype.
I would just use the file extension rather than try to do something clever that may eventually come back to bite you in the arse. 🙂
The file extension doesn’t need to be registered on your system (although I don’t know exactly what you’re doing with the file…). You could use something like an enum or db table which contains information on acceptable extensions if you want to filter out files.
Please see @Tolgahan’s idea on this. I created a C# enum below based on this which should provide people with a starting point should they wish to create a db/enum/xml-based approach to this.