Trim sharepoint's documents

I've come across a strange problem. I download a physical document from the sharepoint custom document library add this document back to the same library - it throw the error "Office document cannot be updated". When I add a document which was created not in the sharepoint - everything were ok. I've investigated deeply this problem and found that when you get a physical document from your custom document library it exported together with fields of the content type. These fields wrote into custom document properties of the document. I foung only one way to get rid of them - use microsoft COM library - word automation(Microsoft.Office.Interop.Word).


object path = "Path to file goes here";
object missing = Missing.Value;
object readOnly = false;
object isVisible = false;
object itemProp;
Type typeItemProp;

Word.Application wApp = new Microsoft.Office.Interop.Word.ApplicationClass();

Word.Document wDoc = wApp.Documents.Open(ref path, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref isVisible, ref missing,
ref missing, ref missing, ref missing);

wDoc.Activate();
try
{
//Sometimes there is exception being thrown - Attempted to read or write protected memory.
wDoc.RemoveDocumentInformation(Microsoft.Office.Interop.Word.WdRemoveDocInfoType.wdRDIAll);
}
catch { }
//Anyway if there are other custom fields available we remove it

object oDocCustomProps = wDoc.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType();
object nrProps = typeDocCustomProps.InvokeMember("Count",
BindingFlags.GetProperty | BindingFlags.Default,
null, oDocCustomProps, new object[] { });

while ((int)nrProps > 0)
{
itemProp = typeDocCustomProps.InvokeMember("Item",
BindingFlags.GetProperty | BindingFlags.Default,
null, oDocCustomProps, new object[] { 1 });

typeItemProp = itemProp.GetType();
typeItemProp.InvokeMember("Delete",
BindingFlags.Default | BindingFlags.InvokeMethod,
null, itemProp, null);

nrProps = typeDocCustomProps.InvokeMember("Count",
BindingFlags.GetProperty | BindingFlags.Default,
null, oDocCustomProps, new object[] { });
}

Comments

Popular posts from this blog

Client-side scripting for Taxonomy/Term Set Fields

SharePoint delegate control is rendered twice

Some thoughts on using Sitecore Habitat for Production codebase