Reputation: 170489
My C# code may be running inside an MVC3 application under IIS (currently 7.5, but I'd like to not depend on a specific version) or elsewhere.
Looks like one way to know that code is running under IIS is to check the current process name, but this approach depends on having a filename string hardcoded.
Is there some programmatic way to detect my code is running under IIS not depending on IIS version?
Upvotes: 16
Views: 8285
Reputation: 37192
Have a look at the HostingEnvironment class, especially the IsHosted method.
This will tell you if you are being hosted in an ApplicationManager, which will tell you if you are being hosted by ASP.NET.
Strictly, it will not tell you that you are running under IIS but I think this actually meets your needs better.
Example code:
// Returns the file-system path for a given path.
public static string GetMappedPath(string path)
{
if (HostingEnvironment.IsHosted)
{
if (!Path.IsPathRooted(path))
{
// We are about to call MapPath, so need to ensure that
// we do not pass an absolute path.
//
// We use HostingEnvironment.MapPath, rather than
// Server.MapPath, to allow this method to be used
// in application startup. Server.MapPath calls
// HostingEnvironment.MapPath internally.
return HostingEnvironment.MapPath(path);
}
else {
return path;
}
}
else
{
throw new ApplicationException (
"I'm not in an ASP.NET hosted environment :-(");
}
}
Upvotes: 30
Reputation: 1443
Have a look at the ServiceController class. The service name will still be hardcoded, but the chances of the service changing name are relatively low.
You could also use netstat -ab
to find out what is running on the port 80.
Upvotes: -3