简体   繁体   中英

Get file path from Visual Studio editor

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

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

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;

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?

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

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. 替代文字

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM