Is there a way to read .csproj PropertyGroup variable in c#

26 Views Asked by At

I'm looking to build selfcontained publishsingle file dotnet application. During dotnet publish, setting the environmentName variable from commandline. Is there a way to read this porpertyGroup variable in c#.

dotnet publish --configuration Release --self-contained true  -p:EnvironmentName=Development -p:PublishSingleFile=true

Project.csproj

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'" >
  <EnvironmentName>Production</EnvironmentName>
</PropertyGroup>

<Choose>
  <When Condition=" '$(EnvironmentName)'=='Production' ">    
    <ItemGroup>
      <Compile Remove="**/Development/*.cs" />
      <Compile Remove="**/Staging/*.cs" />
    </ItemGroup>
  </When>
  <When Condition=" '$(EnvironmentName)'=='Staging' ">
    <ItemGroup>
      <Compile Remove="**/Production/*.cs" />
    </ItemGroup>
  </When>
  <Otherwise>
    ...
  </Otherwise>
</Choose>

C#

internal class Program
{
  private static async Task ConfigureBuilderAsync(IHostBuilder builder, string[] args)
  {
    await builder.UseContentRoot(Directory.GetCurrentDirectory())
    .ConfigureHostConfiguration(builder =>
    {
      ...
       
     // how to read csproj envName here in c#
      var env = Environment.GetEnvironmentVariable("EnvironmentName");
      if (env == "Production")
      {
       _ = builder
        .SetBasePath(basedirectory!)
        .AddJsonFile("appsettings.production.json", false, false)
        .AddUserSecrets<Program>()
        .AddEnvironmentVariables();
      }
      else
      {
        _ = builder
        .SetBasePath(basedirectory!)
        .AddJsonFile($"appsettings.staging.json", true, true)
        .AddJsonFile($"appsettings.development.json", true, true)
        .AddUserSecrets<Program>()
        .AddEnvironmentVariables();
    }
  ...
  }
}
0

There are 0 best solutions below