Search code examples
c#visual-studio-2012envdte

Using C#, how do I "Include" a file into a project?


Thanks for looking.

I have a small program that generates a new .NET solution based on some project information and a database connection.

As part of this process, I automatically generate the ADO.NET entity data model/.edmx file using edmgen2.

This code works fine and generates the .edmx, etc which is added to the project's folder in Windows.

The Problem

When I open the generated solution and subsequently the DAL project which contains the .edmx, I must then show excluded files, right-click, and then include the .edmx manually.

This isn't a huge deal, but it would be nicer if I could call come code after the .edmx is generated that would automatically include it in the VS Project.

Is this possible?

ADDING TO THE ANSWERS BELOW:

The answers below got me going but I did find that I couldn't operate on the .csproj xml in the usual ways that I alter other xml files. You have to use the msbuild namespace. Here is what worked for me:

var csproj = XDocument.Load(SolutionFolder + @"\SomeProject.csproj");
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
var itemGroups = csproj.Descendants(msbuild + "ItemGroup");
var itemGroup = itemGroups.FirstOrDefault(x => x.Descendants(msbuild + "Compile").Any());
var item = new XElement(msbuild + "Compile");
item.SetAttributeValue("Include", "ApplicationEntityModel.edmx");
itemGroup.Add(item);
csproj.Save(SolutionFolder + @"\SomeProject.csproj");

Solution

  • Not tested: You can edit your *.csproj file and add your new file to <ItemGroup> section. It is an xml file that can be edited programitically.

      <ItemGroup>
        <Compile Include="fileName" />
      </ItemGroup>