确定是在没有System.Web的ASP.NET或WinForms / console中运行

时间:2011-03-28 20:58:13

标签: .net asp.net winforms

从类库中,我需要在运行时确定我是在ASP.NET应用程序还是WinForms / console应用程序中运行。关于此主题已有several other questions asked,但所有这些解决方案都需要添加对System.Web的引用。如果可能的话,在运行我的控制台和WinForms应用程序时,我不想将System.Web程序集加载到内存中,只需要为数千行代码中的一行代码。

8 个答案:

答案 0 :(得分:8)

使用System.Diagnostics.Process.GetCurrentProcess().ProcessName

如果您正在运行ASP.NET,那么程序集will be named thusly:

  • 如果您运行的是IIS 6.0或IIS 7.0,则名称为w3wp.exe。

  • 如果您运行的是早期版本的IIS,则名称为aspnet_wp.exe。

另一个想法:如何使用AppDomain.CurrentDomain.GetAssemblies()API测试进程/应用程序域是否存在System.Web.dll?

答案 1 :(得分:5)

您链接的其中一个问题包含answer建议Environment.UserInteractive

您还可以尝试分析代码的StackTrace,以确定调用的位置。

答案 2 :(得分:2)

你可以尝试一些基于Assembly.GetEntryAssembly()的东西。如下面的注释所述,如果当前代码在Web应用程序或服务的上下文中运行,则GetEntryAssembly()将返回NULL。在独立应用程序(如WinForm或控制台应用程序)的情况下,它将返回一些非空引用。

由于评论而被编辑以更改原始答案。

答案 3 :(得分:2)

另一个黑客:

如果您没有在独立的exe内运行,则System.Configuration.ConfigurationManager.OpenExeConfiguration会抛出带有特定消息的ArgumentException。您可以使用这个事实来检查:

bool notAnExe = false ;
try
{
    // see if we're running in an exe.
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
catch(ArgumentException aex)
{
    if(aex.Message == "exePath must be specified when not running inside a stand alone exe.")
    {
        notAnExe = true ;
    }
}

答案 4 :(得分:1)

您可以检查System.Diagnostics.Process.GetCurrentProcess()。ProcessName;。如果它以aspnet开头,那就是asp.net。否则,桌面。

答案 5 :(得分:0)

它可能看起来像一个黑客。它使用DomainManager类型的当前AppDomain。另请查看AppDomainManager

public static class AspContext
{
    public static bool IsAspNet()
    {
        var appDomainManager = AppDomain.CurrentDomain.DomainManager;
        return appDomainManager != null && appDomainManager.GetType().Name.Contains("AspNetAppDomainManager");
    }
}

或者您可以使用this other answer on SO

答案 6 :(得分:0)

这是一个老线程,但这里是一个新的答案,不是黑客。

private bool IsExe()
{
  var domainManager = AppDomain.CurrentDomain.DomainManager;
  if (domainManager == null) return false;

  var entryAssembly = domainManager.EntryAssembly;
  if (entryAssembly == null) return false;

  return entryAssembly.Location.EndsWith(".exe", StringComparison.OrdinalIgnoreCase);
}

这不会告诉你应用程序是否是ASP.Net,但是它会告诉你这是一个控制台还是WinForms应用程序,这是与大多数其他答案相反的方法。例如,如果这是一个OWIN应用程序,IsExe方法将返回false,即使这不是ASP.Net应用程序。

答案 7 :(得分:0)

var fullNameTextField = self.infoRegisterRefferenceVC.fullName.text 

MSDN Docs

相关问题