Getting the icon for a given file extension

Background

In writing a pretty boring LOB app for my day job, I had the need to associate and store arbitrary files with records. I didn't want to just store the file in the actual database, so given that the application already sends audio and image data to an Ftp server on the network I figured I would store the files there also and just hold the file name in the database. 'm not storing the path, just the name and extension of the file and then the file is on the Ftp. Works very well and any client in the building can store pdf/doc/xls/etc files and anyone else can see and save them.  The problem I had was that I wanted to make a nice UI for the workflow and display the correct icon for each file. There is a handy static method for extracting icons from files, Icon.ExtractAssociatedIcon(filePath), which works great when you actually have the path to a file you want to find the icon for. Unfortunately there is no way built into the framework to get the default icon for a given file extension.

The Solution

The solution is to P/Invoke into Shell32.dll and call SHGetFileInfo. This lets us just pass in a file extension and get back an icon, we can also use this to get folder icons. Pretty handy, here is the static method in my class which does the lifting.

SHFILEINFO shellFileInfo = new SHFILEINFO();

try

{

    uint flags = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES;

    flags |= linkOverlay ? SHGFI_LINKOVERLAY : 0;

    flags |= largeIcon ? SHGFI_LARGEICON : SHGFI_SMALLICON;

 

    SHGetFileInfo(extension,

        FILE_ATTRIBUTE_NORMAL,

        ref shellFileInfo,

        (uint)Marshal.SizeOf(shellFileInfo),

        flags);

 

    return (Icon)Icon.FromHandle(shellFileInfo.hIcon).Clone();

}

finally

{

    DestroyIcon(shellFileInfo.hIcon);

}

 

The trick is in passing SHGFI_USEFILEATTRIBUTES, this tells SHGetFileInfo not to look on the disk for this file. Raymond Chen explains is better than I could in his post here.

To illustrate and test the code I knocked up a quick sample app which is included with the download, check it out. 



Just tap in a file extension and select whether you want the shorcut arrow in the bottom corner and away you go. 

IconUtils.zip (11.85 kb)

kick it on DotNetKicks.com  

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList
February 24, 2008 15:22 by Sean
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Comments are closed