jxxx77,
If you are working in Web application (ASP.NET) then you can get content-type of files using
File1.PostedFile.ContentType where
File1 is of File type. So simple.
If you are working in Windows application then Alas!!! there is no ContentType property available for File or FileStream object.
If you look in the registry, under \\HKEY_CLASSES_ROOT, you will find a list of file extensions! And under the file extensions was a key called
ContentType. Ahaaa! An answer! Or so you may think. But as it turns out to you, there is not a ContentType key under ALL the file types, only some of them. Which means this method would only help SOME of the time for some of file types. Since you like to keep your job ALL of the time, you needed a better answer.
For a better repository of content-types, you can use this path
\\HKEY_CLASSES_ROOT\MIME\Database\Content Type\. Finally, here you can find ALMOST complete listing of every ContentType available on that specific machine where the code is to be run. Under each key, a sub-key with the file extenstion that maps to that ContentType. Since I have a filename, all I have to do is match the key to the ContentType.
Code:
Public Function GetMimeType(ByVal filePathArg As String) As String
Dim registryPermission As RegistryPermission = New RegistryPermission(RegistryPermissionAccess.Read, "\\HKEY_CLASSES_ROOT")
Dim hiveClassesRoot As RegistryKey = Registry.ClassesRoot
Dim myFileInfo = New FileInfo(filePathArg)
Dim fileExtension As String = LCase(myFileInfo.Extension)
Dim keyContentType As RegistryKey = hiveClassesRoot.OpenSubKey("MIME\Database\Content Type")
Dim keyName As String
For Each keyName In keyContentType.GetSubKeyNames()
Dim currentKey As RegistryKey = hiveClassesRoot.OpenSubKey("MIME\Database\Content Type\" & keyName)
If LCase(currentKey.GetValue("Extension")) = fileExtension Then
Return keyName
End If
Next
End Function
INFORMATION about Registry Locations to look for MIME types:
[ul]
[li]Location used by FindMimeFromData function to find MIME type and progID from file extension:
HKEY_CLASSES_ROOT\.*** *** represents extension name.[/li]
[li]Location used by FindMimeFromData to find application from progID:
HKEY_CLASSES_ROOT\<ProgId>\shell\open\command[/li]
[li]Location used by URL monikers to find CLSIDs from MIME types:
HKEY_CLASSES_ROOT\MIME\Database\Content Type[/li]
[/ul]
Hope this helps.