Visual Studio 扩展:更改程序集引用的提示路径

Visual Studio extension: Change the hint path of an assembly reference

我正在编写一个 Visual Studio 扩展,我想在不触发 "File Modification Detected" 对话框的情况下更改 C# 项目的程序集引用的提示路径。

<Reference Include="SomeAssembly">
  <HintPath>C:\ChangeMe\SomeAssembly.dll</HintPath>
</Reference>

但是在 VSLangProj110.Reference5 接口中我找不到任何可以使用的 属性。 (通过 VSLangProj140 访问。VSProject3.References)

我创建了一个演示并在我这边重现了你的问题。我认为这是一个设计问题,如果你在环境之外修改项目,它会弹出 "File Modification Detected" 对话框,我们需要手动更改它。

您可以 post 对以下 link 的反馈:https://connect.microsoft.com/VisualStudio/Feedback

更新:

DTE2 dte = (DTE2)this.ServiceProvider.GetService(typeof(DTE));
            EnvDTE.Project currentProject = dte.Solution.Projects.Item(1);

            // Create a new Project object.
            Microsoft.Build.BuildEngine.Project project = new Microsoft.Build.BuildEngine.Project();

            project.Load(currentProject.FullName);

            foreach (BuildItemGroup ig in project.ItemGroups)
            {
                //var items = ig.ToArray();

                foreach (BuildItem item in ig.ToArray())
                {
                    if (item.Include == "ClassLibrary1")
                    {
                        item.Include = "Utils";
                        item.SetMetadata("HintPath", @"C:\relativePath\Utils.dll");
                    }
                }
            }
            project.Save(currentProject.FullName);

Microsoft.Build.BuildEngine.Project 已过时。这是一个更新的工作解决方案。

foreach (var dteProject in dte.Solution.Projects.OfType<Project>())
{
    // You can edit the project through an object of Microsoft.Build.Evaluation.Project 
    var buildProject = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(dteProject.FullName).First();
    foreach (var item in buildProject.Items.Where(obj => obj.ItemType == "Reference"))
    {
        var newPath = SomeMethod(item.GetMetadata("HintPath"));

        item.SetMetadataValue("HintPath", newPath);
    }

    // But you have to save through an object of EnvDTE.Project
    dteProject.Save();
}