sample code for finding type of file based on extension

B

Brian Henry

Just thought maybe someone here would like to know this. It's an example
code I just created quickly on how to figure out the name of a type of file
based on its extension (say for example .DOC) would return "Microsoft Word
Document"... tired doing this before with SHGetFileInfo or what ever its
called, but that seemed to require a phyiscal file to be there, where this
you can just give it a file extension with no file.

Private Function GetNameForExtension(ByVal Extension As String) As String

' open the class root tree in registry and get the node based on the
extension

Dim regProgramKeys As RegistryKey =
Registry.ClassesRoot.OpenSubKey(Extension.Trim)

Dim s_tempName As String = String.Empty

' find the default value of the extensions node, if there is none then use
the extension

Dim s_ClassName As String = regProgramKeys.GetValue("",
Extension.Trim).ToString



' if we got a class name back from the registry for that extension, look up
its name

' else return the extension as the name

If s_ClassName.Trim = Extension.Trim Then

s_tempName = Extension.Trim

Else

' try to look up the class name's formal name, if it doesn't have one return
the extension only

Dim regItemKeys As RegistryKey =
Registry.ClassesRoot.OpenSubKey(s_ClassName)

s_tempName = regItemKeys.GetValue("", Extension.Trim).ToString

End If

Return s_tempName

End Function
 
B

Brian Henry

slight update to that code, since it didn't handle unlisted extensions in
the registry

' returns the name of the type of file based on extension

Public Shared Function GetNameForExtension(ByVal Extension As String) As
String

' open the class root tree in registry and get the node based on the
extension

Dim regProgramKeys As RegistryKey =
Registry.ClassesRoot.OpenSubKey(Extension.Trim)

Dim s_tempName As String = String.Empty

' find the default value of the extensions node, if there is none then use
the extension

If Not regProgramKeys Is Nothing Then

Dim s_ClassName As String = regProgramKeys.GetValue("",
Extension.Trim).ToString



' if we got a class name back from the registry for that extension, look up
its name

' else return the extension as the name

If (s_ClassName.Trim = Extension.Trim) Then

s_tempName = Extension.Trim

Else

' try to look up the class name's formal name, if it doesn't have one return
the extension only

Dim regItemKeys As RegistryKey =
Registry.ClassesRoot.OpenSubKey(s_ClassName)

If Not regItemKeys Is Nothing Then

s_tempName = regItemKeys.GetValue("", Extension.Trim).ToString

Else

s_tempName = Extension.Trim

End If



End If

Else

s_tempName = Extension.Trim

End If

Return s_tempName

End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top