4

I'm developing a Visual Studio Package, written in C#.

How do I get the full path of the active editor programatically?

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219

4 Answers4

3

This is how you get the full path of the focused (active) document in Visual Studio:

DTE dte = (DTE)GetService(typeof(DTE));
string document = dte.ActiveDocument.FullName;
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
3

When working macros you can use

DTE.ActiveDocument.Path + DTE.ActiveDocument.Name

to get the full path. Likely this is the same in C# when making VS packages?

stijn
  • 34,664
  • 13
  • 111
  • 163
2

I had a similar problem when developing ASP.NET Web Forms custom server controls. In order to obtain a reference to the DTE object and create a virtual path to the directory of the file being edited I used the following code inside my custom server control file:

    [Bindable(true)]
    [Category("Behavior")]
    [DefaultValue("")]
    [Editor(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))]
    public string Url
    {
        get
        { 
            object urlObject = ViewState["Url"];
            if (urlObject == null)
            {
                if (DesignMode)
                { 
                    // Get a reference to the Visual Studio IDE
                    EnvDTE.DTE dte = this.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;

                    // Interface for accessing the web application in VS
                    IWebApplication webApplication = (IWebApplication)this.Site.GetService(typeof(IWebApplication));

                    // Path of document being edited (Web form in web application)
                    string activeDocumentPath = dte.ActiveDocument.Path;

                    // Physical path to the web application root
                    string projectPath = webApplication.RootProjectItem.PhysicalPath;

                    // Create virtal path
                    string relativePath = activeDocumentPath.Replace(projectPath, "~\\");

                    return relativePath.Replace('\\','/');
                }
                else
                {
                    return String.Empty;
                }
            }
            else
            {
                return (string)urlObject;
            }
        }
        set
        {
            ViewState["Url"] = value;
        }
    }

This is useful quickly navigating to a file near the one being edited when using the UrlEditor

Tobias
  • 61
  • 2
0

In VS 2010 and 2008, you right click the tab at the top and select "Copy Full Path" from the context menu. See my image below. alt text

Wulfhart
  • 215
  • 1
  • 11