SharePoint. Getting Document Icon URL

docicon.xml

All the icons for files on SharePoint are registered in the file, located at \14\TEMPLATE\XML\DOCICON.XML. Here is a small piece of it:

<?xml version="1.0" encoding="utf-8"?>
<DocIcons>
    <ByProgID>
        <Mapping Key="Excel.Sheet" Value="ichtmxls.gif" EditText="Microsoft Excel" />
    <!-- ... -->
    </ByProgID>
    <ByExtension>
        <Mapping Key="zip" Value="iczip.gif" OpenControl=""/>
        <!-- ... -->
    </ByExtension>
    <Default>
        <Mapping Value="icgen.gif"/>
    </Default>
</DocIcons>

To read this data here is a static class:

/// <summary>
/// Document icons from DOCICON.XML file
/// </summary>
public static class DocumentIcons
{
    private static NameValueCollection ExtensionImages { get; set; }
 
    static DocumentIcons()
    {
        ExtensionImages = new NameValueCollection();
        // Path to docicon.xml file
        var dociconPath = SPUtility.GetGenericSetupPath(@"template\xml") + @"\docicon.xml";
        var fi = new FileInfo(dociconPath);
        using (var stream = fi.OpenText())
        {
            var doc = XDocument.Load(stream);
            var icons = doc.Element("DocIcons");
            var byExt = icons.Element("ByExtension");
            foreach (var ext in byExt.Elements())
            {
                var key = ext.Attribute("Key").Value;
                var val = ext.Attribute("Value").Value;
                ExtensionImages.Add(key, "/_layouts/images/" + val);
            }
        }
    }
 
    /// <summary>
    /// Getting document icon URL by file extension
    /// </summary>
    /// <param name="extension">Extension without dot</param>
    /// <returns>URL of icon</returns>
    public static string GetIconUrl(string extension)
    {
        return ExtensionImages[extension] ?? "/_layouts/images/ICGEN.GIF";
    }
}

You can use it, for example, by creating a property in your class representing any document like this:

/// <summary>
/// Icon URL
/// </summary>
public string IconUrl
{
    get
    {
        // Get file extension
        var ext = System.IO.Path.GetExtension(ServerUrl);
        if (ext.Length > 0)
        {
            // Cut off leading dot
            ext = ext.Substring(1);
            // Return icon&for extension
            return DocumentIcons.GetIconUrl(ext);
        }
        // Return default icon
        return DocumentIcons.GetIconUrl(string.Empty);
    }
}

PDF-file icon

To display the icon for pdf-files in SharePoint document library, it is enough to register it in the ByExtension section:

<Mapping Key="pdf" Value="icpdf.png"/>

And place icon into \14\TEMPLATE\IMAGES folder.

Tags

Share

Vitaly Zhukov

Vitaly Zhukov

Tech Lead, Architect, Developer, Technical Trainer, Microsoft MVP. Over 20 years of experience in system integration and software development. I specialize in designing and implementing scalable, high-performance software solutions across various industries.