Robin Rodricks
Robin Rodricks

Reputation: 114126

Conditionally skip compilation of C# source files

I need to include certain source files only if my project is in certain bulid configurations. Is this possible?

I've currently duplicated Debug and Release and created DebugAlt and ReleaseAlt. I need to compile certain forms only in Debug and Release, and exclude them in the alternate configs.

Can I write something like this into the .csproj file?

 <Compile Include="frmTools.cs" Condition="CONFIG=Debug OR Config=Release"/>

Update:

According to the MS Build docs this is supposed to be possible with something like this:

<Choose>
    <When Condition="'$(Configuration)'=='Debug'">
        <ItemGroup>
            <Compile Include="frmTools.cs">
              <SubType>Form</SubType>
            </Compile>
        </ItemGroup>
    </When>
</Choose>

This works halfways; The project loads perfectly but frmTools NEVER compiles. Its because the When condition always evaluates to false. Why? What have I done wrong?

Upvotes: 1

Views: 1364

Answers (2)

Robin Rodricks
Robin Rodricks

Reputation: 114126

I finally got it working with this. Looking up the DefineConstants array allows you to check if a certain constant var has been defined, and include/exclude source files accordingly.

<Choose>
    <When Condition="$(DefineConstants.Contains('MYCONST'))">
        <ItemGroup>
            <Compile Include="frmTools.cs">
              <SubType>Form</SubType>
            </Compile>
        </ItemGroup>
    </When>
</Choose>

Instead of checking which project config is active, we simply add a const to a few project configs and then check the const value in the Project XML.

Upvotes: 1

Dirk Huber
Dirk Huber

Reputation: 912

You can use http://msdn.microsoft.com/library/ms164307.aspx therefore.

Please consider that you need to edit the project file manually in a text editor, Visual Studio does not allow you to edit this via GUI.

However, you can still open the projects in Visual Studio.

Upvotes: 1

Related Questions