Msbuild ms生成引擎查找现有项或删除重复项
我目前正在开发一个生成C代码文件并将其添加到现有项目中的应用程序。要编辑项目,我正在使用Microsoft.Build.BuildEngine,并将现有的.csproj文件加载到项目类中Msbuild ms生成引擎查找现有项或删除重复项,msbuild,code-generation,Msbuild,Code Generation,我目前正在开发一个生成C代码文件并将其添加到现有项目中的应用程序。要编辑项目,我正在使用Microsoft.Build.BuildEngine,并将现有的.csproj文件加载到项目类中 csproj = new Project(new Engine(),"3.5"); csproj.Load("/myproject.csproj"); 在此之后,我可以添加引用并根据需要编译项。但是,我不知道这些文件或引用是否已经在.csproj文件中,所以目前它们被添加了多次,这是我不想要的 例如:
csproj = new Project(new Engine(),"3.5");
csproj.Load("/myproject.csproj");
在此之后,我可以添加引用并根据需要编译项。但是,我不知道这些文件或引用是否已经在.csproj文件中,所以目前它们被添加了多次,这是我不想要的
例如:
<Reference Include="System" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Core" />
有人知道在我将builditem添加到项目之前检查它是否存在的方法吗?或者是在我添加了重复的builditems之后删除它们的方法?您可以遍历项目对象的EvaluatedItems 此示例代码演示如何在添加builditem之前检查其存在性:
// 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");
}
}
这是一个如何删除重复的项目
// 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);
}
}