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

时间:2015-12-08 16:48:24

标签: c#

填空:

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

网络应用 - > System.Web.HttpContext.Current != null

WCF网络服务 - > 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不会抛出异常。

我已经考虑过使用试用版,但这并不适合我的情况。

1 个答案:

答案 0 :(得分:2)

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

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