Microsoft added a new feature in Visual Basic 2005 (and is present in 08 as well) that will very easily get the icon associated with a specified file. In the past you would have to use the Windows APIs to extract a icon from a file. But now you can use a feature in Version 2.0 and higher of the DotNET Framework to perform this task which is what this little tip will show.
The function to use is ‘ExtractAssociatedIcon’ that is located under the System.Drawing.Icon namespace.
Public Shared Function ExtractAssociatedIcon(ByVal filePath As String) As System.Drawing.Icon
As you can see this is a very simple function. All you need to do is specify the path of the file whose icon you want to extract and handle the return value of the function which is the Icon associated with the file specified in the filePath parameter.
The code below will get the Icon associated with the file I specified and display the Icon in a Picturebox control.
picSource.Image = Drawing.Icon.ExtractAssociatedIcon(“pathAndFileToGetIcon”).ToBitmap()
Using the code above, i’m using a picturebox that I named picSource while converting the Icon to a Bitmap which can then be displayed easier in the picturebox image property. IF you want to save the icon image displayed in the picturebox control, the small piece of code below will do the trick.
Well, thats all there is to it I guess. Since MS added this ‘ExtractAssociatedIcon’ Function to the framework you no longer have to use the APIs to get similar results if your using Visual Basic .NET 2005 or version 2008. Have Fun!