polyvertex
polyvertex

Reputation: 829

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.

Upvotes: 5

Views: 2267

Answers (2)

polyvertex
polyvertex

Reputation: 829

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!

Upvotes: 5

Bernhard Hiller
Bernhard Hiller

Reputation: 2397

I am not sure where your problem is located. I have a similar requirement that a file is created by the program which just was compiled. I edited the properties of the project: in the build events enter a Post-build action like

REM create special file
"$(ProjectDir)$(OutDir)MyProgram.exe" /WriteFile MyFile.xml

Of course, you must also change your program such that it does the right thing when called with that parameter (and stops after having completed that action - does not show a GUI or start as a Windows Service).

Upvotes: 0

Related Questions