【发布时间】:2010-10-24 04:15:15
【问题描述】:
有谁知道如何在 C# 代码中获取当前的构建配置$(Configuration)?
【问题讨论】:
标签: c# configuration
有谁知道如何在 C# 代码中获取当前的构建配置$(Configuration)?
【问题讨论】:
标签: c# configuration
.NET 中有AssemblyConfigurationAttribute。您可以使用它来获取构建配置的名称
var assemblyConfigurationAttribute = typeof(CLASS_NAME).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
var buildConfigurationName = assemblyConfigurationAttribute?.Configuration;
【讨论】:
<?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"]
【讨论】:
你不能,不是真的。 您可以做的是定义一些“条件编译符号”,如果您查看项目设置的“构建”页面,您可以在那里进行设置,这样您就可以编写#if语句来测试它们。
为调试构建自动注入一个 DEBUG 符号(默认情况下,可以关闭它)。
所以你可以这样写代码
#if DEBUG
RunMyDEBUGRoutine();
#else
RunMyRELEASERoutine();
#endif
但是,除非你有充分的理由,否则不要这样做。在调试版本和发布版本之间使用不同行为的应用程序对任何人都没有好处。
【讨论】:
您可以使用带有条件属性的通用静态方法来设置标志以检测 DEBUG 或 RELEASE 模式。 SetDebugMode 方法只有在 DEBUG 模式下运行时才会被调用,否则会被 Runtime 忽略。
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);
【讨论】:
条件编译符号可以用来实现这一点。您可以在 Properties > Build settings 窗格中为每个项目定义自定义符号,并使用 #if 指令在代码中对其进行测试。
显示如何定义符号 UNOEURO 以及如何在代码中使用它的示例。
bool isUnoeuro = false;
#if UNOEURO
isUnoeuro = true;
#endif
【讨论】:
如果您卸载项目(在右键菜单中)并将其添加到 </Project> 标记之前,它将保存一个包含您的配置的文件。然后,您可以将其读回以在您的代码中使用。
<Target Name="BeforeBuild">
<WriteLinesToFile File="$(OutputPath)\env.config"
Lines="$(Configuration)" Overwrite="true">
</WriteLinesToFile>
</Target>
【讨论】:
我不相信您可以在编译时将其注入程序集,但您可以实现它的一种方法是使用 MSBuild 并将其添加到应用程序的配置文件中。
请参阅这篇关于如何使用 MSBuild 进行多环境配置文件的博文 - http://adeneys.wordpress.com/2009/04/17/multi-environment-config/
或者,您可以编写一个 MSBuild 任务,该任务将编辑某个编译文件(您的 C# 或 VB 文件)并在 BeforeBuild 任务中运行。这会相当棘手,因为您需要确定将其注入文件的位置,但只要您设置了某种标记化,您应该能够做到。我也怀疑它会不会漂亮!
【讨论】: