Change base directory of a site in IIS

This technique works for IIS6 and IIS7 with the “IIS 6 WMI Compatibility* installed. The purpose is changing the directory of a web site in a remote server. The purpose of this action will be clear in a future post, for now only assume that you want to be able to create a piece of c# code that changes directory of a web site in windows server. Here is a test site.

image

Now if you run this code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "administrator";
connection.Password = "xxxxxx";
connection.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope scope = new ManagementScope(@"\\WS2008V1\root\MicrosoftIISv2", connection);

//get Fixed disk stats
System.Management.ObjectQuery query =
    new System.Management.ObjectQuery("select * from IIsWebVirtualDirSetting where AppPoolId= 'test'");

//Execute the query 
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

//Get the results
ManagementObjectCollection oReturnCollection = searcher.Get();
ManagementObject site = oReturnCollection
   .Cast<ManagementObject>()
   .Single();
site["Path"] = @"C:\inetpub\wwwroot";
site.Put();

And if you look at site directory again you will get.

image

So you have changed the Physical path of the application.

The code is really simple, you need to add reference to System.Management to use WMI, then you create a ConnectionOptions class to specify credentials to use. To access MicrosoftIISv2 object it is really important that you set AuthenticationLevel to PacketPrivacy. Then you simply need to query for IIsWebVirtualDirSetting using AppPoolId to find the application you want, then simply use a ManagementObjectSearcher to issue the query, and finally use LINQ to grab the only result, change the Path property and update modification with Put() method.

Alk.

Tags: IIS