How to add new dll reference programmatically using microsoft.build.evaluation

650 views Asked by At

I am trying to remove one reference and replace it with new reference for multiple C# projects.

How do I add new reference using microsoft.build.evaluation

using Microsoft.Build.Evaluation;
var projCollection  =  new ProjectCollection();
var proj =  projCollection.LoadProject(csproj_filepath);

var items  = proj.GetItems("Reference");

foreach(var item in items)
{
 if(item. EvaluatedInclude.Equals("XYZ_reference"))
  {
   //remove this reference
   // add new reference with new hint path etc
  }
}
proj.Save();

There is documentation here, but not very useful in terms of difference between with and without metadata include or usage example.

1

There are 1 answers

0
UserName On

I do not quite understand what exactly the problem is. For ex: small snippet from my old project for replacing PackageReference with ProjectReference for easier debugging locally:

    private void SwitchExplicitPackage(MSProject.Project project, NugetPackage package, Dictionary<string, string> projects)
    {
        ProjectItem item = project.GetItemsByEvaluatedInclude(package.Identity).FirstOrDefault();

        if (item == null)
            return;

        /*
         * Metadata is needed for compatibility with classic projects.
         */

        MSProject.Project newProject = _projectHelper.GetLoadedProject(projects[package.Identity]);

        item.UnevaluatedInclude = projects[package.Identity];

        item.SetMetadataValue(REF_METADATA_PACKAGE, package.Identity);
        item.SetMetadataValue(REF_METADATA_PROJECT, newProject.GetPropertyValue("ProjectGuid"));
        item.SetMetadataValue(REF_METADATA_NAME   , newProject.GetPropertyValue("ProjectName"));

        item.ItemType = PROJECT_REF; // ProjectReference

        _journalHelper.AddMessage($"Explicit dependency { package.Identity } switched to { projects[package.Identity] }", TaskErrorCategory.Message);
    }

In fact, it all comes down to finding the needed reference and replacing the attributes. After saving, Visual Studio detected the changes and requested to reload the project, after which the changes were applied.