从 Visual Studio 编辑器获取文件路径

4

我正在开发一个用C#编写的Visual Studio扩展程序。

如何通过编程方式获取活动编辑器的完整路径?

4个回答

3
这是在 Visual Studio 中获取当前文档完整路径的方法:

DTE dte = (DTE)GetService(typeof(DTE));
string document = dte.ActiveDocument.FullName;

3

在处理宏时,您可以使用以下方法:

DTE.ActiveDocument.Path + DTE.ActiveDocument.Name

获取完整路径。在制作VS扩展时,可能与C#相同?


2

在开发ASP.NET Web Forms自定义服务器控件时,我遇到了类似的问题。为了获得对DTE对象的引用并创建编辑文件所在目录的虚拟路径,我在自定义服务器控件文件中使用了以下代码:

    [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;
        }
    }

使用UrlEditor时,这是快速导航到正在编辑的文件附近的有用方法。


0
在 VS 2010 和 2008 中,您可以右键单击顶部的选项卡,然后从上下文菜单中选择“复制完整路径”。请参见下面的图片。 alt text

2
我从问题中推断出,OP的意思是以编程方式。 - Tim Lloyd
我认为这不是原帖作者所寻找的。 - Neil N
我并不经常希望能够投票将一个答案移动到姐妹站点之一,但现在我确实希望这样做。 - Ben Voigt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接