by Robert
22. March 2011 16:48
Today, I came across a need to programmatically rename IIS 7 Virtual Directories and Applications using C#. Searching the web, I found several examples to add them, but wasn't able to find any to rename them. By exploring the class methods and modifying the examples accordingly, I was able to come up with what I was looking for.
Note: The ServerManager class is within the Microsoft.Web.Administration namespace - the dll to reference can be found in the system IIS directory (%WinDir%\System32\InetSrv).
Rename IIS 7 Virtual Directory
ServerManager iisManager = new ServerManager();
Application app = iisManager.Sites["SiteName"].Applications["/"];
VirtualDirectory vdir = app.VirtualDirectories["/OrigVirtualDirectoryName"];
if (vdir != null)
{
vdir.SetAttributeValue("path", "/NewVirtualDirectoryName");
iisManager.CommitChanges();
}
Rename IIS 7 Application
ServerManager iisManager = new ServerManager();
Application app = iisManager.Sites["SiteName"].Applications["/OrigApplicationName"];
if (app != null)
{
app.SetAttributeValue("path", "/NewApplicationName");
iisManager.CommitChanges();
}
If you want to work with a remote server, just change the first line to be
ServerManager iisManager = ServerManager.OpenRemote("RemoteServerName");