简体   繁体   中英

Detect win or web forms

Any reliable elegant way of detecting whether the current app is a win or web forms (or other) application?

We have a common config class which needs to open either app.config or web.config.

Currently, I'm catching ArgumentException when I try OpenExeConfiguration but it's not very elegant and might mask other issues.

I usually check if there's a HttpContext available (if it's a Web Application since in a Web Service HttpContenxt.Current is null) To do this, you should add System.Web to your references.

if(HttpContext.Current!=null)
//It's a web application
else
//it's a win application

尝试使用依赖项注入,以便config类不必执行switch语句。

You could try getting the executing process via Process.GetCurrentProcess() , possibly you could check the Process.MainWindowHandle is not IntPtr.Zero , or check the process name, or potentially scan the loaded modules of the Process. This would have an advantage (I would assume) of not requiring your to load assemblies that are not required for your current execution context (eg don't load System.Windows.Forms.dll when that app is a web app).

However this seems inelegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM