MSBuild in Visual Studio Part 7: Reading Items From the Project File

I don’t know about everyone else, but I’m pretty sick of escaping and properties [:)] It’s time to move on to the other major way the project system leverages MSBuild, and that’s the wonderful world of items. After all, without items there’d be no way to list the files you want compiled or the resources that should get included!

If you’ve spent any time at all messing around with project files you’ve probably noticed that some item names have special meaning to Visual Studio. A few of the most popular are Compile, Reference, COMReference, ProjectReference, Folder, and Import.

Reading items is pretty straightforward. The only special thing the project system does is use Project.EvaluatedItemsIgnoringCondition to get the list of items to display. What exactly does this mean? Imagine you had the following in your project file:

  <ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">

    <Compile Include="Properties\AssemblyInfo.cs" />

    <Compile Include="XmlLogger.cs" />

  </ItemGroup>

During the build process this will do exactly as you expect: AssemblyInfo.cs and XmlLogger.cs will only get added to the Compile group if the configuration is Release|AnyCPU. This condition is completely irrelevant, however, when the project is viewed in Visual Studio. This is primarily because it was just way too complicated to try and figure out how to deal with all the UI issues that would arise from this. The project team decided it would be far simpler to just display all items in the project file, regardless of condition.

Even though conditions can’t be used to tweak item display in Visual Studio, the visibility of items be controlled using the project file XML. If you have some items that you want to participate in the build process, but you want to hide them in Solution Explorer, add the Visible metadata like this:

  <Compile Include="Properties\AssemblyInfo.cs">

    <Visible>false</Visible>

  </Compile>

If no metadata for visibility is specified, Visual Studio makes items in the project visible and items from imported files invisible. This ensures items from .targets files don’t show up by default.

 

The only other interesting aspect of reading items from the project file is the ability to add a custom BuildAction element to the UI using item groups. We’ve covered how to add this through .targets files in an earlier post, but you can also do it through a project file: Visual Studio will add any item name declared in an ItemGroup to the dropdown as well.

 

That’s about all there is to say on reading items. Stay tuned for our next entry, where we’ll explore the intricacies of writing items back out to project files.

[ Author: Neil Enns ]