有人知道如何在C#代码中获取当前构建配置$(Configuration)
吗?
在.NET中有一个叫做AssemblyConfigurationAttribute的东西。你可以使用它来获得构建配置的名称。
var assemblyConfigurationAttribute = typeof(CLASS_NAME).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
var buildConfigurationName = assemblyConfigurationAttribute?.Configuration;
</Project>
标记之前,它将保存一个包含您配置的文件。然后,您可以将其读回以在代码中使用。<Target Name="BeforeBuild">
<WriteLinesToFile File="$(OutputPath)\env.config"
Lines="$(Configuration)" Overwrite="true">
</WriteLinesToFile>
</Target>
更新
这个问题的答案在Egor在这个答案列表中提供的答案(这里)。
你不能真正地做到这一点。
你可以定义一些“条件编译符号”,如果你查看项目设置的“构建”页面,你可以在那里设置它们,这样你就可以编写#if语句来测试它们。
对于调试版本,默认情况下会自动注入DEBUG符号(这可以关闭)。
因此,您可以编写如下代码:
#if DEBUG
RunMyDEBUGRoutine();
#else
RunMyRELEASERoutine();
#endif
然而,除非你有充分的理由,否则不要这样做。一个在调试构建和发布构建之间具有不同行为的应用程序对任何人都没有好处。
可以使用条件编译符号来实现此目的。您可以在每个项目的属性>构建设置窗格中定义自定义符号,然后使用#if指令在代码中测试它们。
以下示例展示了如何定义符号UNOEURO以及如何在代码中使用它。
bool isUnoeuro = false;
#if UNOEURO
isUnoeuro = true;
#endif
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="Build" value="" />
</appSettings>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<!--For more information on using transformations see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="Build" value="Debug" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
</appSettings>
</configuration>
ConfigurationManager.AppSettings["Build"]
public static class AppCompilationConfiguration
{
private static bool debugMode;
private static bool IsDebugMode()
{
SetDebugMode();
return debugMode;
}
//This method will be loaded only in the case of DEBUG mode.
//In RELEASE mode, all the calls to this method will be ignored by runtime.
[Conditional("DEBUG")]
private static void SetDebugMode()
{
debugMode = true;
}
public static string CompilationMode => IsDebugMode() ? "DEBUG" : "RELEASE";
}
Console.WriteLine(AppCompilationConfiguration.CompilationMode);
我不相信你可以在编译时将其注入到程序集中,但你可以使用MSBuild并将其添加到应用程序的配置文件中来实现它。
请参阅这篇关于如何使用MSBuild进行多环境配置文件的博客文章 - http://adeneys.wordpress.com/2009/04/17/multi-environment-config/
或者,您可以编写一个MSBuild任务,该任务将编辑某个已编译文件(您的C#或VB文件),并在BeforeBuild
任务中运行它。这可能会非常棘手,因为您需要确定将其注入到文件的哪个位置,但只要您设置了某种标记化,就应该能够做到。我也怀疑它是否会很漂亮!