首页 > 解决方案 > .net Core 获取已启动应用程序的配置

问题描述

如何在 C# .Net Core 中获取已启动应用程序的配置

我知道我可以这样做:

public static string Get_Configuration() {
      string conf = "Release";
#if DEBUG
       conf = "Debug";
#endif
      return conf;
}

但它看起来不太好,有什么想法可以做得最漂亮吗?

在此处输入图像描述

标签: c#.net-core

解决方案


我想你需要的是构建平台。

构建平台在编译时嵌入在 DLL/EXE 中。

我不确定目的是什么,以及您要创建的 API 究竟应该输入什么。因此,我提出了几个选项,我相信它们可以帮助您解决问题。

选项 1:使用程序集属性

在这种情况下,您可以有条件地将程序集配置属性应用于程序集。然后在运行时,您可以检查应用于 DLL/EXE 的程序集属性。

#if (Debug || DEBUG)
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif

选项 2:使用 C# 代码

有一种方法来自Scott Hanselman 的博客,它采用程序集名称并决定程序集是否使用发布模式构建。

public static int GetBuildType(string AssemblyName)
{
    Assembly assm = Assembly.LoadFrom(AssemblyName);
    object[] attributes = assm.GetCustomAttributes(typeof(DebuggableAttribute), false);
    if (attributes.Length == 0)
    {
        Console.WriteLine(String.Format("{0} is a RELEASE Build....", AssemblyName));
        return 0;
    }

    foreach (Attribute attr in attributes)
    {
        if (attr is DebuggableAttribute)
        {
            DebuggableAttribute d = attr as DebuggableAttribute;
            Console.WriteLine(String.Format("Run time Optimizer is enabled : {0}", !d.IsJITOptimizerDisabled));
            Console.WriteLine(String.Format("Run time Tracking is enabled : {0}", d.IsJITTrackingEnabled));

            if (d.IsJITOptimizerDisabled == true)
            {
                Console.WriteLine(String.Format("{0} is a DEBUG Build....", AssemblyName));
                return 1;
            }
            else
            {
                Console.WriteLine(String.Format("{0} is a RELEASE Build....", AssemblyName));
                return 0;
            }
        }
    }
    return 3;
}

选项 3:PowerShell 脚本

在同一个博客上,您可以找到一些也可以使用的 powershell 脚本。

根据您的目的和轻松程度,您可以选择任何一个选项。

希望这可以帮助。


推荐阅读