Get Custom Document Properties / Document Information Panel Values using C#

Object: To retrieve custom document properties of office documents using C#.
Generally, it is required to get or set custom document properties programmatically. For example, when document is checked out from sharepoint server then document information panel shows server properties. Our object is to modify the properties using C# in word. But problem is document type. Before office 2007, the document is binary file and in Office 2007, it is compressed XML file. Here is the sample code to do this. In the code, all the properties name are passed as hashtable keys.

//Collection of all column Names
Hashtable ht = new Hashtable();
//Collection of name and values of custom document properties
List<ListItem> lstTags = new List<ListItem>();
//Active Document
Microsoft.Office.Interop.Word.Document objDoc;

void LoadValuesFromDocuments(Hashtable ht)
{
//Office 2007 Documents
if (objDoc.Name.ToLower().EndsWith("docx"))
{
//Load Document Information Panel
XmlDocument InfoPathXML = new XmlDocument();
InfoPathXML.LoadXml(objDoc.CustomXMLParts[4].XML);
//Log("XML: "+ Doc.CustomXMLParts[4].XML);
foreach (string str in ht.Keys)
{
try
{
ListItem lstItem = new ListItem();
lstItem.Text = str;
lstItem.Value = InfoPathXML.SelectSingleNode("//*[local-name(.)='" + ht[str].ToString() + "']").InnerText;
lstTags.Add(lstItem);
}
catch (Exception ex)
{
Log(ex.ToString());
}
}
}
else            //Old Documents
{
foreach (string str in ht.Keys)
{
try
{
ListItem lstItem = new ListItem();
lstItem.Text = str;
lstItem.Value = ((DocumentProperties)objDoc.CustomDocumentProperties)[str].Value.ToString();
lstTags.Add(lstItem);
}
catch (Exception ex)
{ Log(ex.ToString()); }

}

}
}


To set values for older version documents (NOT Office 2007 docs)
try
{                   
((DocumentProperties)objDoc.CustomDocumentProperties)[fieldName].Value = fieldValue;                   
// Add and Remove sample text to indicate msword that the document is modified so that It will pass 
// DIP info to sharepoint even there is no change in content.
object startPosition = 0;
object endPosition = 0;                    
Range r = objDoc.Range(ref startPosition, ref endPosition);
r.InsertAfter("this is test.");
object unit = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
object count = 1;
r.Delete(ref unit, ref count);
}
catch (Exception ex)
{
Log(ex.ToString());                  
}

Hope! It helps.

No comments:

Post a Comment