Work out the type of c# application a class contained in a DLL is being used by

血红的双手。 提交于 2019-11-30 18:08:30

问题


Is there any way to know in C# the type of application that is running.

Windows Service ASP.NET Windows Form Console

I would like to react to the application type but cannot find a way to determine it.


回答1:


You should have the client code tell your code what the context is and then work from that. At best, you will be able to guess based on external factors.

If you must guess, this is what I would look for:

  • For ASP.NET, I would look for HttpContext.Current
  • For Windows Forms, I see if the static OpenForms collection on the Application class has any items in it.
  • For Windows Presentation Foundation, see if the static Current property on the Application class is not null.
  • For a service, there really is no way to determine this, since services do not have to register process handles, thread handles, or the like.
  • For console windows, if none of the above is true, then I would assume this is a console.



回答2:


Try checking Application.MessageLoop. It should be true for Windows Forms applications (that have a WinForms message loop), and false for windows services. I don't know what it would return for ASP.NET.

As for console applications, they would have no message loop so they would return false. You can check for that using most properties in the Console class, but I warn you that it's a HACK. If you must, I'd go with:

bool isConsole = Console.In != StreamReader.Null;

Note, that a console app could still call Console.SetIn(StreamReader.Null) or a windows app could call Console.SetIn(something else), so this is easily tricked.




回答3:


ASP.NET, check the if HttpContext.Current is null




回答4:


To check for a Forms, WPF, WCF or Console application:

if (System.Windows.Forms.Application.OpenForms.Count > 0)
{
    return ApplicationType.WindowsForms;
}

if (System.Windows.Application.Current != null)
{
    return ApplicationType.Wpf;
}

if (System.ServiceModel.OperationContext.Current != null)
{
    return ApplicationType.Wcf;
}

try
{
    int windowHeight = Console.WindowHeight; // an exception could occur
    return ApplicationType.Console;
}
catch (IOException)
{
}

return ApplicationType.Unknown;


来源:https://stackoverflow.com/questions/563677/work-out-the-type-of-c-sharp-application-a-class-contained-in-a-dll-is-being-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!