有没有办法在 运行 时间告诉 运行 正在使用哪种类型的应用程序 c# 代码?

is there a way to tell at run time which type of app c# code is running in?

在 Visual Studio 2022 .sln 中有 2 个项目。一个是 Windows 服务,另一个是 ASP.NET 6.0。两者都使用共享代码从 app.config 文件中检索 xml 数据,例如 SQL 服务器实例名称、数据库名称等。

对于日志记录,我使用 log4net 包,它在我的 Windows.Service 项目目标 .NET Framework 4.6.1 和我的 ASP.NET 目标的 .NET Core 中实现有些不同。

为了省事我想写一个通用的日志方法,里面区分平台。

那么,有没有办法获取代码是 运行 的应用程序类型?

您无法获取应用程序类型,但您可以获得目标框架,我相信这会解决您的问题。

        Assembly currentAssembly = Assembly.GetExecutingAssembly();

        var attribute = currentAssembly.GetCustomAttribute<System.Runtime.Versioning.TargetFrameworkAttribute>();

        if (attribute.FrameworkName == ".NETCoreApp,Version=v3.1")
        {
            //Do Stuff
        }

如果我需要澄清任何事情,请告诉我。

编码愉快:)