gpt4 book ai didi

c# - 如何检查上下文是 Windows 服务还是控制台应用程序

转载 作者:行者123 更新时间:2023-11-30 23:32:50 25 4
gpt4 key购买 nike

填空:

如果 DLL 上的一段代码在不同的上下文中使用,我们需要确定我们在哪个上下文中运行,我们必须使用:

Web 应用程序 -> System.Web.HttpContext.Current != null

WCF Web 服务 -> System.ServiceModel.Operationcontext.Current != null

Windows 服务 || ConsoleApp -> __________________________________________________________

此外,如果您知道检查前两个选项之一的更好选项,请告诉我们。

关于它可能与 another question 重复的事实: 我不需要区分 Windows 服务和控制台应用程序(用户交互与否)。

编辑:我为什么需要它?

我需要从可以在不同上下文中运行的库中打开正在运行的应用程序的配置文件。这是我目前拥有的:

Configuration appConfig = null;

if (System.Web.HttpContext.Current != null || System.ServiceModel.OperationContext.Current != null)
{
// The call was originated from a web application or from a WCF web service.
appConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
// The call may have been originated from a console application or a windows service.
// THE ANSWER TO MY SO QUESTION WOULD ALLOW ME TO INSERT AN IF HERE!!
appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}

其他部分假设我在类似 exe 的环境(Windows 服务、控制台应用程序)上运行。我想在其中包含一个 if 以确保 OpenExeConfiguration 不会抛出异常。

我已经考虑过使用 try block ,但这不适合我的情况。

最佳答案

我认为这是一个非常脆弱的结构,但如果你检查是否 AppDomain.CurrentDomain.SetupInformation.ConfigurationFile以字符串 web.config 结尾 您可以验证当前应用程序域是否在 Web 服务器中运行,因此您可以调用 System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 获取Configuration实例。

反之亦然:如果它以 .exe.config 结尾,您可以使用 ConfigurationManager.OpenExeConfiguration(...)

关于c# - 如何检查上下文是 Windows 服务还是控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34161455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com