Getting open document by name – Extending Visual Studio SharePoint development tools tip #7

One of the many great things that the Visual Studio SharePoint development tools allow you to do is to help you automate and simplify working with SharePoint content without leaving Visual Studio. Knowing how to retrieve a document opened in Visual Studio using its name, is one of the basic things you need to know to make your extension really powerful.


In your project you need the following assembly references:

  • EnvDTE (Embed Interop Types: True)
  • EnvDTE80 (Embed Interop Types: True)
  • Microsoft.VisualStudio.OLE.Interop
  • Microsoft.VisualStudio.Shell
  • Microsoft.VisualStudio.Shell.Interop
  • Microsoft.VisualStudio.Shell.Interop.8.0

You can also paste the following snippet into your project file:

<Reference Include="EnvDTE, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">  
<Reference Include="EnvDTE80, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">  
<Reference Include="Microsoft.VisualStudio.OLE.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />  
<Reference Include="Microsoft.VisualStudio.Shell, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />  
<Reference Include="Microsoft.VisualStudio.Shell.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />  
<Reference Include="Microsoft.VisualStudio.Shell.Interop.8.0, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />  


public static Document GetOpenDocument(string name, Documents documents)  
    Document document = null;

    int numDocs = documents.Count;
    for (int i = 1; i <= numDocs; i++)
        Document d = documents.Item(i);
        if (d.Windows.Item(1).Caption.Equals(name, StringComparison.InvariantCultureIgnoreCase))
            document = d;

    return document;

The working of the GetOpenDocument method is very simple. What it does is it iterates through the collection of documents opened in Visual Studio and then compares the caption each window to the name passed as parameter. To find the file the GetOpenDocument method uses the caption of the window instead of the name of the file, because files, that haven’t been saved yet, use temporary file names which are different from the caption displayed in the tab of the current document.


DTE2 dte = Package.GetGlobalService(typeof(SDTE)) as DTE2;  
Document document = GetOpenDocument("TextFile1.txt", dte.Documents);  
if (document != null)  
    TextSelection ts = document.Selection;

Shows the contents of the TextFile1.txt file opened in Visual Studio:

Showing contents of a file opened in Visual Studio obtained using the GetOpenDocument method

Technorati Tags: SharePoint 2010,Visual Studio 2010


comments powered by Disqus