Search code examples
c#msbuildvcxproj

Write Properties (name=value) to a file from an MSBuild project


For an MSBuild project, I would like to output some kind of a .config file that would be redistributed along the generated binary so the parameters used at build time can be checked by the users of the binary, programmatically.

Output file format:

PropertyName1=ValueA
PropertyName2=ValueB
...

Ideally, the list of properties to write would contain just their names. Maybe like:

<ItemGroup>
  <MyExposedDictionary Include="Configuration" />
  <MyExposedDictionary Include="Platform" />
  <MyExposedDictionary Include="PropertyName1" />
  ...
</ItemGroup>

With MyExposedDictionary being the argument to give to some DotConfigFileWriter task, as well as the path of the destination file.

I found several ways to write down values to a file, including a sub-target with some C# code in it, but I'm new to MSBuild and I'm not sure how I can merge those requirements into a single Target to make it re-usable.


Solution

  • In case someone comes here with the same requirement, here is what I ended up with. Not really happy with the result as I was hoping for something more generic but at least it does the job and blends well in my project:

    <Target Name="WriteBuildProperties" BeforeTargets="PreBuildEvent">
      <WriteLinesToFile File="$(DotConfigFile)" Overwrite="true" Lines="" />
      <WriteLinesToFile File="$(DotConfigFile)" Lines="ProjectName=$(ProjectName)" />
      <WriteLinesToFile File="$(DotConfigFile)" Lines="Configuration=$(Configuration)" />
      ...
    </Target>
    

    If someone happen to have a more elegant solution, please jump in!