Using Sharepoint’s File Type Icons

We have an old web part that displays documents from a list, and shows an icon next to file. After reading the list, the web part has a long “if-else” block that checks the files extension and displays the proper image. The images come from sharepoint template directory. I need to update this web part to display more file types icons. At first we though to create a list that maps images to extensions, but after little research I’ve decided to read sharepoint’s docicon.xml file.
First, we need to find the file docicon.xml. The file usually sits under

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\template\xml\docicon.xml

The xml directory is not mapped on the IIS, but we can still find it using this little trick:

string path = MapPathSecure("~/_layouts/");
path = Path.Combine(path, @"..\xml\docicon.xml");

Now all that’s left is to read the xml and add the data to a collection:
(This is actually the first time using XmlDataReader, but how wrong can I be?)
First, we define two members, for all files and the default icon, and then go through the XML nodes:

protected NameValueCollection fileTypeIcons;
protected string defaultIcon;

protected void readIconsXml()
{
    XmlReader reader = XmlReader.Create(path);
    reader.ReadToFollowing("ByExtension");
    //find the first child. This doesn't skip the first node.
    reader.ReadToFollowing("Mapping");
    while (reader.ReadToNextSibling("Mapping"))
    {
        readOneNodeMapping(reader);
    }
    //find the default icon
    reader.ReadToFollowing("Default");
    reader.ReadToFollowing("Mapping");
    defaultIcon = reader.GetAttribute("Value");
}

protected void readOneNodeMapping(XmlReader reader)
{
    string tempKey = null;
    string tempValue = null;
    tempValue = reader.GetAttribute("Value");
    tempKey = reader.GetAttribute("Key");
    if ((tempKey != null) && (tempValue != null))
        fileTypeIcons.Add(tempKey, tempValue);
}

And that’s it. We have all icons defined in the site ready in our project.

Advertisements

2 thoughts on “Using Sharepoint’s File Type Icons

  1. Why don’t you just use the following?

    SPUtility.MapToIcon(yourSPWeb, “http://yourserver/yourlist/youdoc.pdf”, string.Empty);

    I think it might be easier… 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s