views:

78

answers:

1

I am currently working on an application that generates C# code files and adds them to an existing project. To edit the project I'm using Microsoft.Build.BuildEngine, and loading the exisiting .csproj file into the Project class.

csproj = new Project(new Engine(),"3.5");
csproj.Load("/myproject.csproj");   

After wich I am able to add refeneces and compile items as I need. However I do not know if the files or references are already in the .csproj file, so currently they get added multiple times, which I do not want.

for example:

    <Reference Include="System" />
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Core" />

Does anyone know of a way I can check if a builditem exists before I add it to the project? Or of a way to remove duplicated builditems after I've added them?

A: 

You could iterate through the EvaluatedItems of your Project Object

This sample code demonstrates how to check builditem existence before adding it :

// Create a new Engine object.
Engine engine = new Engine(Environment.CurrentDirectory);

// Create a new Project object.
Project csproj = new Project(new Engine(),"3.5");
csproj.Load("/myproject.csproj"); 

BuildItemGroup referenceItemGroup;
var currentReferences = new HashSet<string>();

// Iterate through each ItemGroup in the Project.
foreach (BuildItemGroup ig in csproj.ItemGroups)
{ 
  // Iterate through each Item in the ItemGroup.
  foreach (BuildItem item in ig)
  {
    if (item.Name == "Reference")
    {
      currentReferences.Add(item.Include);
      referenceItemGroup = ig;
    }
  }
}

// Add only non existing reference
if (!currentReferences.Contains("NewReferenceToAdd"))
{
  if (referenceItemGroup != null)
  {
    referenceItemGroup.AddNewItem("Reference", "IncludeValue");
  }
}

And this one how to remove duplicates item

// Create a new Engine object.
Engine engine = new Engine(Environment.CurrentDirectory);

// Create a new Project object.
Project csproj = new Project(new Engine(),"3.5");
csproj.Load("/myproject.csproj"); 

var currentReferences = new HashSet<string>();

// Iterate through each ItemGroup in the Project.
foreach (BuildItemGroup ig in csproj.ItemGroups)
{
  var itemsToRemove = new List<BuildItem>;

  // Iterate through each Item in the ItemGroup.
  foreach (BuildItem item in ig)
  {
    if (item.Name == "Reference")
    {
      if (currentReferences.Contains(item.Include))
      {
        itemsToRemove.Add(item);
      }
      else
      {
        currentReferences.Add(item.Include);
      }
    }
  }

  // Remove duplicate items
  foreach (BuildItem itemToRemove in itemsToRemove)
  {
    ig.RemoveItem(itemToRemove);
  }
}
madgnome