Nick Grattan's Blog

About Microsoft SharePoint, .NET, Natural Language Processing and Machine Learning

Posts Tagged ‘SharePoint C# Programming

Opening SharePoint documents for Edit from Client Applications

with 7 comments

The ActiveX component “SharePoint.OpenDocuments” is used to open SharePoint documents ready for editing. It is documented here and is usually called from JScript code in a web page. But what about if you want to open a SharePoint document from a client application, such as a .NET WinForm or WPF application?

You might try the following code using the full URL to the document:

System.Diagnostics.Process.Start(docUrl); 

This will open the document in the client application (e.g. Microsoft Word), but it will always be opened read-only.

The following code will create an version specific instance of SharePoint.OpenDocuments and then call the EditDocument method to open the document:

        public static void OpenDocumentForEdit(string docUrl)
        {
            Type t = null;
             // get the correct version specific version...
            t = Type.GetTypeFromProgID("SharePoint.OpenDocuments.1");
            if (t == null)
                t = Type.GetTypeFromProgID("SharePoint.OpenDocuments.2");
            if (t == null)
                t = Type.GetTypeFromProgID("SharePoint.OpenDocuments.3");

            if (t == null)
            {
                System.Diagnostics.Process.Start(docUrl);    // best we can do, will open read-only
                return;
            }
            Object o = Activator.CreateInstance(t);
            object[] openParms = { docUrl, string.Empty };
            t.InvokeMember("EditDocument",
                System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
                null, o, openParms);
        }

Note that different versions of Office install different versions, and this code attempts to open the version installed on the client application. If none could be found it opens the document, albeit in read-only mode. When the method is called the following dialog will be presented to the user:

Written by Nick Grattan

December 31, 2010 at 7:29 pm