【问题标题】:Generate C# using MSBuild使用 MSBuild 生成 C#
【发布时间】:2019-03-01 01:25:55
【问题描述】:

我有一个生成 cs 文件的批处理文件。新的 cs 文件存储在我的一个项目解决方案中。

这是我的 msbuild 任务的 sn-p:

<Target Name="MyDummyGenerator" BeforeTargets="Build">
    <Message Text="Generating file" />
    <Exec Command="./path_to_batch_file/dummy.bat" ContinueOnError="false" />
</Target>

问题是我生成的文件没有列在要编译的文件中,也不是程序集的一部分。尝试使用 &lt;Compile Include="MyGeneratedFile.cs"&gt; 将此文件隐式添加到 csproj 文件后,出现此错误(MyGeneratedFile.cs 是从批处理文件写入的文件: "包含了重复的“内容”项。.NET SDK 默认包含您项目目录中的“内容”项

顺便说一句 - 再次编译时,生成文件是程序集的一部分,但这是因为文件在开始整个构建步骤之前就在项目源中......

我什至尝试在 PreBuild 事件中运行它,但没有成功。

使用 msbuild 生成 c# 代码的正确方法是什么? PS我正在使用.net Framework 4.7.1

【问题讨论】:

  • 您使用的是哪个 .NET 框架?
  • 4.7.1(我会更新主帖)
  • 可以添加批处理文件的内容吗?
  • 它只是写一个cs文件内容。例如 @@echo off @@echo // 这里是 C# 文件内容 例如 > MyFile.cs

标签: c# .net msbuild code-generation msbuild-task


【解决方案1】:

我猜这篇文章回答了这个问题: https://mhut.ch/journal/2015/06/30/build-time-code-generation-in-msbuild

简而言之,您需要在编译(或智能感知)开始之前挂钩 CoreCompile 目标以生成您的文件,并在目标内生成一个 Compile 项。 有关如何在构建期间创建项目的详细信息,请参阅此文档: https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild-items?view=vs-2019#create-items-during-execution

此外,您应该将文件生成到中间输出(obj 文件夹),而不是在源中生成,以免弄乱。 在下面的示例中,输入和输出主要用于 MSBUILD 在文件更改时知道要刷新的内容。

<Target Name="UpdateGeneratedFiles"
  DependsOnTargets="_UpdateGeneratedFiles"
  Condition=="'@(ResourceFile)' != ''"
>
  <ItemGroup>
    <Compile Include="$(IntermediateOutputDir)GeneratedFile.g.cs" />
    <!-- see https://mhut.ch/journal/2016/04/19/msbuild_code_generation_vs2015
    <FileWrites Include="$(IntermediateOutputDir)GeneratedFile.g.cs" />
    -->
  </ItemGroup>
</Target>
<Target Name="_UpdateGeneratedFiles"
  Inputs="$(MSBuildProjectFile);@(ResourceFile)"
  Outputs="$(IntermediateOutputDir)GeneratedFile.g.cs"
>
  <FileGenerationTask
      Inputs="@(ResourceFile)"
      Output="$(IntermediateOutputDir)GeneratedFile.g.cs"
  >
</Target>

【讨论】:

  • 对我来说是 $(IntermediateOutputPath),而不是 $(IntermediateOutputDir)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 2020-05-04
相关资源
最近更新 更多