Search code examples
c#.netvisual-studiomsbuildcsproj

How can I read a value from appSettings.config in CSPROJ conditional


I would like to read an option out of my appSettings.config file to create a conditional section in my CSPROJ. I know how to do the conditional references with help from visual studio 2010 conditional references but I am not sure how to access the appSettings file from within.

Is this possible and if so, could someone provide some guidance please.

EDIT Following @palo's answer I now have:

<Target Name="BeforeBuild">
        <XmlPeek XmlInputPath="SiteSettings.config" Query="appSettings/add[@key='cProjectNumber']/@value">
            <Output TaskParameter="Result" ItemName="value" />
        </XmlPeek>
        <Message Text="TESTING: @(value)" Importance="high" />
    </Target>

This works well and prints out the project number i.e Testing: 012. Now, how do I go about using it in some compile includes? I have tried:

<ItemGroup>
    <Compile Include="Accounts\@(value)\Controls\MyControl.ascx.cs">
        <SubType>ASPXCodeBehind</SubType>
    </Compile>
</ItemGroup>

But I get an error saying:

The expression "Accounts\@(value)\Controls\MyControl.ascx.cs" cannot be used in this context. Item lists cannot be concatenated with other strings where an item list is expected. Use a semicolon to separate multiple item lists.


Solution

  • Following @palo's answer I came up with the following (I will mark this as the answer as it details information on how to achieve what I wanted):

    <Target Name="BeforeBuild">
        <XmlPeek XmlInputPath="SiteSettings.config" Query="appSettings/add[@key='cProjectNumber']/@value">
            <Output TaskParameter="Result" ItemName="value" />
        </XmlPeek>
        <Message Text="TESTING: @(value)" Importance="high" />
        <PropertyGroup>
            <ProjectNumber>@(value)</ProjectNumber>
        </PropertyGroup>
        <ItemGroup>
            <Compile Include="Accounts\$(ProjectNumber)\Controls\MyControl.ascx.cs">
                <SubType>ASPXCodeBehind</SubType>
            </Compile>
        </ItemGroup>
    </Target>
    

    With an XML structure like:

    <appSettings>
      <add key="cProjectNumber" value="123" />
    </appSettings>