Wednesday, March 1, 2017

Retrieve SharePoint Document Icons programmatically

Environment: SharePoint Server 2013


Requirement: Retrieve SharePoint Document library icon based on the document type (extension).


Solution: Use SPUtility.GetCurrentGenericSetupPath to obtain the file path for sharepoint 2013 location and use System.IO.File.Exists() method to check if the file exists in the location.


Following method returns the file name and relative URL of the icon file location based on the extension parameter passed.


       /// <summary>
       /// Method to get the document icon path
       /// </summary>
       /// <param name="extn">document type</param>
       /// <returns>relative URL of the icon image file</returns>
       public static string GetDocumentIconPath(string extn)
       {
           try
           {
               if (File.Exists(SPUtility.GetCurrentGenericSetupPath("template\\images\\ic" + extn + ".png")))
                   return "_layouts/15/images/ic" + extn + ".png";
               else if (File.Exists(SPUtility.GetCurrentGenericSetupPath("template\\images\\ic" + extn + ".gif")))
                   return "_layouts/15/images/ic" + extn + ".gif";
               else
                   return "_layouts/15/images/icgen.gif";
           }
           catch (Exception ex)
           {
              //Handle Exception
           }
       }


//Call the above method by passing the File Type column value of a document library item.
String iconURL = GetDocumentIconPath(document.Item["File Type"].ToString();

No comments:

Post a Comment