[英]How to obtain build configuration at runtime?
有誰知道如何在 C# 代碼中獲取當前的構建配置$(Configuration)
?
如果你卸載你的項目(在右鍵菜單中)並在</Project>
標簽之前添加它,它將保存一個包含你的配置的文件。 然后您可以將其讀回以在您的代碼中使用。
<Target Name="BeforeBuild">
<WriteLinesToFile File="$(OutputPath)\env.config"
Lines="$(Configuration)" Overwrite="true">
</WriteLinesToFile>
</Target>
你不能,不是真的。 您可以做的是定義一些“條件編譯符號”,如果您查看項目設置的“構建”頁面,您可以在那里進行設置,以便您可以編寫#if 語句來測試它們。
調試符號會自動注入(默認情況下,可以關閉)用於調試版本。
所以你可以寫這樣的代碼
#if DEBUG
RunMyDEBUGRoutine();
#else
RunMyRELEASERoutine();
#endif
但是,除非您有充分的理由,否則不要這樣做。 在調試和發布版本之間以不同行為工作的應用程序對任何人都沒有好處。
可以使用條件編譯符號來實現這一點。 您可以在“屬性”>“構建設置”窗格中為每個項目定義自定義符號,並使用 #if 指令在代碼中測試它們。
示例顯示如何定義符號 UNOEURO 以及如何在代碼中使用它。
bool isUnoeuro = false;
#if UNOEURO
isUnoeuro = true;
#endif
.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"]
您可以使用帶有條件屬性的通用靜態方法來設置標志以檢測 DEBUG 或 RELEASE 模式。 只有在 DEBUG 模式下運行時才會調用 SetDebugMode 方法,否則它會被 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);
我不相信您可以在編譯時將其注入程序集,但實現它的一種方法是使用 MSBuild 並將其添加到應用程序的配置文件中。
請參閱有關如何使用 MSBuild 執行多環境配置文件的博客文章 - http://adeneys.wordpress.com/2009/04/17/multi-environment-config/
或者,您可以編寫一個 MSBuild 任務,該任務將編輯某個編譯文件(您的 C# 或 VB 文件)並在BeforeBuild
任務中運行該BeforeBuild
。 這會相當棘手,因為您需要確定將其注入文件的位置,但是如果您設置了某種標記化,您應該能夠做到。 我也懷疑它會漂亮!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.