我如何在 C# 中快速处理 csproj 文件

How do i Quickly Process a csproj file in c#

我正在制作一个预编译器,这意味着它将读取大量文件并处理一些自定义预处理器指令。但无论我在网上看多少,我都找不到 .csproj 文件的工作处理器。我可以阅读它们并提取数据。但我无法处理它们以使用配置和平台参数提取状态。

我的意思是,如果我有一个 csproj,它在 DEBUG 构建中添加了一些预处理器指令,而在 RELEASE 构建中添加了其他指令,我希望能够处理该文件,以便在构建 DEBUG 时我正确获取所有然后定义的预处理器,同样适用于 RELEASE 版本。

我将具体处理 dotnet 核心项目。

I want to get the file state after processing all conditions using the Platform and Configuration. this includes stuff like OutputPath, AllowUnsafe, BuildTargets and such.

c# 编译器与 c++ 编译器不同,没有特定的 预编译 指令项元素指定给编译器,如 PreprocessorDefinitions

作为建议,您可以尝试添加自定义 target in xxxx.csproj file to execute some msbuild task 来做一些预处理。如果您想在 pre-build 目标之后执行所有这些操作,您只需将 AfterTargets="PrepareForBuild" 设置为该自定义目标,这意味着它会在 PrepareForBuild 目标之后运行。

建议

就像这样:

<Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild">

<Message Importance="high" Text="$(OutputPath)--$(AllowUnsafeBlocks)--$(PrepareForBuildDependsOn)" ></Message>

 ........//other msbuild task

 </Target>

1)如果要以配置为条件,根据Debug执行不同的前置指令或者 Release,你可以使用 MSBuild conditions。 如果要使用Debug,可以参考这个:

<Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild" Condition=" '$(Configuration)' == 'Debug' ">

同时,如果你也想添加palform作为并行条件,请试试这个:

 <Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild" Condition=" '$(Configuration)' == 'Debug' and '$(Platform)' =='Any CPU' ">

2) 由于 outputpathAllowUnsafe 是 MSBuild 属性,您可以使用 $(outputpath)$(AllowUnsafeBlocks) 来获取它们值,而您可以使用 @(...) 获取 MSBuild items.

的值

3) 基本上,在target中执行一个预指令,你可以用一个任务来完成,你可以参考this document添加任何你想要的任务做任何操作。