MSBuild: Item Groups (2 of 7)

November 29th, 2006

An ItemGroup in an MSBuild script defines a list or collection of items. These items are typically files. Often you may use a collection to define a static set of files which exist prior to the build running, but sometimes the build generates output files which are not. In the latter case there is a different approach you must use in defining an ItemGroup definition.

The example below defines a property which is used when defining a collection in the ItemGroup.

If there are any files in $(ApplicationOutputDirectory) they will be included in the collection. To reference this collection of files, you use @(ZipFiles). Notice that instead of a dollar sign it uses an @ sign. A dollar sign is for scalar values while the @ sign denotes a collection.

The above definition is how you would define a collection of files, but what if the files are created by the build run with the MSBuild script? Implicit in the name of the ApplicationOutputDirectory property is that it is the output of a build. If there are no files in the output directory prior to the build the collection will be empty. As a result, as you reference that collection it will not list any files. This is because the ItemGroup is defined at startup and not redefined later. This is the intended behavior, but it is not intuitive. You might expect, as I did, that the wildcards would be evaluated when the reference is used. That is not the case.

What you would want to do is cause the ItemGroup definition to be established after the build has created files in the output folder. That can be done with CreateItem. The example below defines a collection called ZipFiles which is then used by the Zip Task.

Before I had learned how to use CreateItem to create the ItemGroup definition after the build I simply had a script called Package Build.cmd which would run the MSBuild script twice. On the first pass it called the Build target and on the second pass it called the Package target. I just accepted the fact that if the build did fail, it would still continue on and call the second pass and create the zip file. With this revised approach I know that the zip file will always carry output assemblies which have compiled successfully.

More Information:

Next is this series, dependencies.

One Response to “MSBuild: Item Groups (2 of 7)”

  1. MSBuild: Item Groups (2 of 7) :: Newstack Says:

    [...] Read more: here [...]