I have a code library that works in ASP.NET, the SQL CLR, and stand-alone applications, and provides different features based on whether certain namespaces (such as System.Drawing) are available or not. Right now, I’m excluding those pieces of code manually, but it would be beneficial to have the C# compiler to it:
- I could be lazier,
- I could use one and the same library.
I know I can use #if directives to search for defines, and I could manually define something like ASP_NET, but if there’s a way to do this automatically, that’d be even greater.
So, can I detect ASP.NET? Alternatively, can I detect whether certain referenced assemblies are available?
There is no such predefined pre-processor directive for asp.net.
What most people do is look for the current
HttpContext– the assumption being that if it is null, this is not a web context.Another alternative is testing
HttpRuntime.AppDomainAppIdfor null, to the similar assumption.Other similar options:
And you can check that a
web.configfile exists.