September 12, 2012

Finding App Deployment Directory from Azure WebRole

Finding which directory a Windows Azure application is deployed to is fairly straight forward for a WorkerRole, but for a WebRole hosted in IIS can be rather challenging!

This issue particularly manifests itself when your WebRole deployment contains any "data" files (such as config files) which need to be accessed from your ASP.NET application code, but can potentially be an issue from role startup code too.

The main reason this problem occurs for IIS WebRole's is because when an ASP.NET app is hosted in IIS the assemblies containing code-behind logic are run from a separate location managed by IIS, and this runtime location is not directly related to the directory containing the rest of the deployment files for that WebRole in any way.

Here is a little utility function that finds the deployment directory location for both WebRole's and WorkerRole's - usable from either role startup code and/or web application code.

public static DirectoryInfo AzureAppDirectory
{
    get
    {
        string appRoot;
        string roleRootDir = Environment.GetEnvironmentVariable("RoleRoot");
        if (roleRootDir == null)
        {
            appRoot = HttpContext.Current.Server.MapPath(@"~\");
        }
        else
        {
            Assembly assy = Assembly.GetExecutingAssembly();
            appRoot = Path.GetDirectoryName(assy.Location);
        }
        var appDir = new DirectoryInfo(appRoot);
        if (!appDir.Exists)
        {
            throw new FileNotFoundException("Cannot find Azure approot directory", appDir.FullName);
        }
        return appDir;
    }
}
Update: Minor tweak to allow code to be used from web role startup code when running from IIS web role.
Entry categories: Cloud Services Dot NET Programming
Posted by Jorgen Thelin at September 12, 2012 03:35 PM - [PermaLink]