How to programmatically change the physical directory for a web app in IIS 7.x

Security Briefs

Syndication

There’s lots of info out there on using Microsoft.Web.Administration to configure IIS programmatically. I personally found most of it rather confusing, and I spent way too much time trying to figure this out, calling GetApplicationHostConfiguration, etc.

There’s a dead simple way to do this that I finally found.

Notes about this code:

  • The collections return null if they don’t have the thing you are looking for. I’m not checking for that in this sample code.
  • Don't forget to include a slash in front of your app name.

Edit later same day: Updated code to be more robust by not assuming first vdir is root. Now the code searches for a vdir named "/" under the app.

using Microsoft.Web.Administration;
class Program
{
    // add reference to System.Web
    // and %WINDIR%\system32\inetsrv\Microsoft.Web.Administration.dll
    static void Main()
    {
        const string WebsiteName = "Default Web Site";
        const string AppName = "/test"; // Note: starts with slash
        const string NewPhysicalPath = @"c:\temp\newDir";

        using (var serverManager = new ServerManager())
        {
            var site = serverManager.Sites[WebsiteName];
            var app = site.Applications[AppName];
            var vdir = FindAppVdir(app);
            vdir.PhysicalPath = NewPhysicalPath;
            serverManager.CommitChanges();
        }
    }

    private static VirtualDirectory FindAppVdir(Application app)
    {
        return app
            .VirtualDirectories
            .FirstOrDefault(vdir => vdir.Path == "/");
    }
}

Posted May 21 2010, 07:30 AM by keith-brown
Filed under: ,