15

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?

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979

2 Answers2

29

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 :-(");
    }
}
RB.
  • 36,301
  • 12
  • 91
  • 131
-3

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.

pikzen
  • 1,413
  • 1
  • 10
  • 18
  • 1
    Just because IIS is running on port 80 doesn't mean his application is being hosted in IIS. The converse is also true - IIS could be running on any other port (e.g. 8080) – RB. Apr 19 '12 at 08:11
  • True. That's why the ServiceController class is recommended. – pikzen Apr 19 '12 at 08:13
  • 3
    All ServiceController can do is tell you whether the IIS service is running, not whether the current code is running in that IIS. – Mark Aug 27 '13 at 21:10