Search code examples
c#.netmsbuilddotnet-publish

How to write batch files correctly for publication Adding different precompiled macros during .NET programming?


I have the following code:

#if PC
    var rootPath = Path.Combine("dist");
#else
    var rootPath = Path.Combine(@"/bin/bash");
#endif

I want to write different batch files when publishing the program to decide whether to add the macro "PC" or not.

But I didn't find the answer under the dotnet publish command.


Solution

    1. Add a configuration (Pc) in your .csproj file, and add the PC symbol:

      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Pc|AnyCPU'">
          <DefineConstants>$(DefineConstants);PC</DefineConstants>
      </PropertyGroup>
      

      Use -c option to pick this configuration:

      dotnet publish -c:Pc
      
    2. Use msbuild's -getProperty and -p options to define the symbols:

      SET cmdGetProp='dotnet msbuild -getProperty:DefineConstants'
      FOR /F "tokens=*" %%s IN (%cmdGetProp%) DO SET prop=%%s
      dotnet publish -p:DefineConstants=\"%prop%;PC\"