Hi,
I am not sure where I got the origin of this code, but it was helpful for me.
private DirectoryEntry _iisServer;
public IISAdmin(string serverName)
{
_serverName = serverName;
}
public IISAdmin()
{
_serverName = "localhost";
}
~IISAdmin()
{
_iisServer.Dispose();
_iisServer = null;
}
public void Connect(string username,string password)
{
try
{
if (string.IsNullOrEmpty(username))
_iisServer = new DirectoryEntry("IIS://" + _serverName + "/w3svc");
else
_iisServer = new DirectoryEntry("IIS://" + _serverName + "/w3svc", username, password);
}
catch (Exception e)
{
throw new Exception("Could not connect to: " + _serverName, e);
}
}
public List<keyvaluepair><string,>> GetAvailableWebSites()
{
List<keyvaluepair><string,>> retVal = new List<keyvaluepair><string,>>();
foreach (DirectoryEntry o in _iisServer.Children)
{
if (o.SchemaClassName == WebServerSchemaName)
{
if (o.Properties["ServerComment"] != null && o.Properties["ServerComment"].Count > 0)
retVal.Add(new KeyValuePair<string,>(o.Name, (string)o.Properties["ServerComment"][0]));
else
retVal.Add(new KeyValuePair<string,>(o.Name, "[website]"));
}
}
return retVal;
}
public void CreateVirtualDirectory(int WebHostId, string nameDirectory, string realPath)
{
DirectoryEntry WebsiteEntity = null;
DirectoryEntry folderRoot = null;
foreach (DirectoryEntry o in _iisServer.Children)
if (o.Name == WebHostId.ToString())
{
WebsiteEntity = o;
folderRoot = o.Children.Find("Root", VirDirSchemaName);
break;
}
if (folderRoot == null) throw new Exception("Website couldnot found!");
try
{
DirectoryEntry newVirDir = folderRoot.Children.Add(nameDirectory, VirDirSchemaName);
newVirDir.Invoke("AppCreate", true);
newVirDir.Properties["AppFriendlyName"].Insert(0, nameDirectory);
newVirDir.Properties["AccessRead"].Insert(0, true);
newVirDir.Properties["Path"].Insert(0, realPath);
newVirDir.CommitChanges();
folderRoot.CommitChanges();
WebsiteEntity.CommitChanges();
_iisServer.CommitChanges();
}
catch (Exception e)
{
throw new Exception("Virtual Directory " + nameDirectory + " Already Exists", e);
}
}
</keyvaluepair></keyvaluepair></keyvaluepair>
Hope it can help you.