Using SharePoint file icons for custom controls

SharePoint already provides icons for files, mainly in lists. You can also make use of those same icons, for example, for custom web parts or controls.

SharePoint's file icons in lists
SharePoint's file icons in lists

First, we need to know where and how SharePoint stores these icons.

The icon images are stored in the images folder in the 12 hive:

Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES
SharePoint's icons folder in the 12 hive
SharePoint's icons folder in the 12 hive

This maps to the virtual directory:

/_layouts/images

There is also an XML file with information of how to map a file type or extension with the appropriate icon. This file can be found at:

Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\DOCICON.xml
SharePoint's DOCICON.xml
SharePoint's DOCICON.xml

If you want to add icons for unknown file types or update existing icons, you can customize the DOCICON.xml file and place the image files in the above-mentioned images folder.

To do this association programmatically, SharePoint provides the method MapToIcon available in the SPUtility class in the Microsoft.SharePoint.Utilities namespace.

To retrieve the path for the icon image, the following code can be used:

string iconPath = "/_layouts/images/" + SPUtility.MapToIcon(web, filename, string.Empty);
  • The first parameter is the web where the file is located (usually SPContext.Current.Web).
  • The second is the filename for the file (e.g. "test.docx").
  • The third parameter is an ID "of the application that was used to create the file" (you can provide an empty string for this argument).

To help retrieve the filename of a file, there is also another useful method: GetUrlFileName. By passing the URL to this method, it retrieves the filename. E.g.:

string filename = SPUtility.GetUrlFileName("http://test.mossdevdomain.com/SiteCollectionDocuments/test.docx");
Nuno Freitas
Posted by Nuno Freitas on August 27, 2013

Related articles