Displaying the Document Type Icon in a DVWP in SharePoint

Oftentimes you’d like to mimic the out of the box display capabilities of SharePoint when you create a view using a DVWP (Data View Web Part or Data Form Web Part).  One of the things you might like to do is to show the document type icon for the documents in your view.  These are the little icons that you see in views where you display the Type column for a Document Library, but you might want to show these icons in other cases as well.

By default, these icons are stored in _layouts/images.  This maps to the C:/Program Files/Common Files/Microsoft Shared/web server extensions/12/TEMPLATE/IMAGES folder in the SharePoint hive.  If you look in that folder, you will see thousands of images, but most of the document type icons take the form IC[Document Type].GIF.  So the Microsoft Word icon is ICDOC.GIF.

The information about which icon is displayed for each document type in stored in the DOCICON.XML file which is stored in the hive at C:/Program Files/Common Files/Microsoft Shared/web server extensions/12/TEMPLATE/XML.

The DOCICON.XML file contains mappings for the document type values (the document extensions):

<Mapping Key="doc" Value="icdoc.gif" EditText="Microsoft Office Word" OpenControl="SharePoint.OpenDocuments" />

as well as for the program IDs:

<Mapping Key="Word.Document" Value="ichtmdoc.gif" EditText="Microsoft Office Word" OpenControl="SharePoint.OpenDocuments" />

Finally, the DOCICON.XML file contains a default icon to use in case there isn’t anything specific about the document type or program ID for the specific file.  By default, this is the icgen.gif icon — the generic icon.

This is all well and good, but how do you take advantage of this well thought out scheme?  Well, the trusty yet surprisingly undocumented ddwrt: namespace comes to the rescue once again.  (Thank goodness for this article from Serge van den Oever or all of this would be an unknown mystery.)

There are two ddwrt functions that you can take advantage of here: GetFileExtension and MapToIcon.  So, all of this complexity can come down to one simple line to display the document type icon:

<img alt="Type" src="/_layouts/images/{ddwrt:MapToIcon('', ddwrt:GetFileExtension(string(@FileLeafRef)))}"/>

In this example, I want to display the document type icon for a file stored in a Document Library, so I am using the @FileLeafRef column (friendly name: Name).  First I call GetFileExtension to pull out the file extension (e.g., doc).  Note the type conversion to string.  As I have mentioned in previous posts, many of the ddwrt: functions require this explicit conversion.  Next, I pass that file extension to the MapToIcon function.  The MapToIcon function takes two arguments: Program ID and File Extension.  Since I don’t know or care about the Program ID in this case, I leave it blank and just pass in the File Extension.  All set: the compound function passes me back the document type icon, easy as pie.