views:

68

answers:

3

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.

+1  A: 

Try using dependency injection so the config class doesn't have to do a switch statement.

ooo
+2  A: 

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

Beatles1692
Thanks, that's what I was looking for
John B
A: 

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 (e.g. don't load System.Windows.Forms.dll when that app is a web app).

However this seems inelegant.

Phil Price
Thanks Phil, this would fail if it's a service though as the service has no MainWindowHandle either.I wanted to avoid interrogating the running process as it seems rather hacky.
John B