jayarjo jayarjo -4 years ago 159
C# Question

C#: Is it possible to conditionally exclude some files from compilation?

I would like to conditionally compile a project excluding specific classes. Is it possible?


Basically what I'm looking for is to decrease the size of resulting .xap file through command-line directive by not compiling in specific classes (stored in separate .cs files) and all their dependencies.

Here is how MSDN recommends to do it manually. If there was a way to do it conditionally in an automated manner, that'd be a perfect solution.

Answer Source

Project file ProjectName.cproj is a plain xml file containing project properties and compiler instructions. Files to include are listed between <ItemGroup>...</ItemGroup> tags. There can be one or more such <ItemGroup> listings. So everything you have to do is put files that you want to be compiled in conditionally, into a separate <ItemGroup> and add a condition as attribute:

<ItemGroup Condition=" '$(BUILD)' == 'IMAGE' ">
    <Compile Include="PngEncoder\Adler32.cs" />
    <Compile Include="PngEncoder\CRC32.cs" />
    <Compile Include="PngEncoder\Deflater.cs" />
    <Compile Include="PngEncoder\DeflaterConstants.cs" />
    <Compile Include="PngEncoder\DeflaterEngine.cs" />
    <Compile Include="PngEncoder\DeflaterHuffman.cs" />
    <Compile Include="PngEncoder\DeflaterOutputStream.cs" />
    <Compile Include="PngEncoder\DeflaterPending.cs" />
    <Compile Include="PngEncoder\IChecksum.cs" />
    <Compile Include="PngEncoder\PendingBuffer.cs" />
    <Compile Include="PngEncoder\PngEncoder.cs" />

Now this group of files will be included only if there is a property defined with the name of BUILD and the value of "IMAGE". Properties can be defined in the project file itself:

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

Or passed in from command-line:

msbuild ProjectName.cproj /p:BUILD=IMAGE

msbuild.exe comes with .NET Framework.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download