Monday, February 13, 2012

Get Document Path from SharePoint Library in VSTO


While working with VSTO AddIn, there was a need to get the source path of the document while it is being opened from a SharePoint document library.
After little efforts, managed to find the property like

Globals.ThisAddIn.Application.ActiveDocument.Path;

But this works only when you open an existing document from the library and not when you try to create new document.
Was wondering for some time that why is this behavior shown by Word APIs?? But MS forums helped a lot.
There are two ways to get the document path / source URL when you open the new document from document library.

1. Get the template of the document and then retrieve source / path of the template. Generally all template path returns something like – http://siteurl/doclibname/forms/templatename
Template template = Globals.ThisAddIn.Application.ActiveDocument.get_AttachedTemplate() as Template;
string path = template.Path;

2. Environment.CommandLine returns the string using which you can get the source of the document. Some formatting is needed which can be done like this
public string GetDocLibPath()
{
  string path = string.Empty;
  string[] tempArray = Environment.CommandLine.Split(new char[] { '"' }, StringSplitOptions.RemoveEmptyEntries);
  if (tempArray.Length >= 3)
  {
string[] temp2Array = tempArray[2].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
       if (temp2Array.Length == 3)
       {
          path = temp2Array[2];
       }
               
   }
  return path;
 }

References: MSDN Forums | MSDN Forums

No comments:

Post a Comment