技术开发 频道

C#中操作IIS 7.0

  然后是对虚拟目录的操作,包括创建和删除虚拟目录,都比较简单。

CreateVDir
public static void CreateVDir(string siteName, string vDirName,
string physicalPath)
{
    
using (ServerManager mgr = new ServerManager())
    {
        Site site
= mgr.Sites[siteName];
        
if (site == null)
        {
            
throw new ApplicationException(String.Format
(
"Web site {0} does not exist", siteName));
        }
        site.Applications.Add(
"/" + vDirName, physicalPath);
        mgr.CommitChanges();
    }
}


DeleteVDir
public static void DeleteVDir(string siteName, string vDirName)
{    
    
using (ServerManager mgr = new ServerManager())
    {
        Site site
= mgr.Sites[siteName];
        
if (site != null)
        {
            Microsoft.Web.Administration.Application app
=
site.Applications[
"/" + vDirName];
            
if (app != null)
            {
                site.Applications.Remove(app);
                mgr.CommitChanges();
            }
        }
    }
}

  删除应用程序池。

DeletePool
/// <summary>
/// Delete an existent web site app pool.
/// </summary>
/// <param name="appPoolName">
App pool name for deletion.</param>
public static void DeletePool(string appPoolName)
{
    
using (ServerManager mgr = new ServerManager())
    {
        ApplicationPool pool
= mgr.ApplicationPools[appPoolName];
        
if (pool != null)
        {
            mgr.ApplicationPools.Remove(pool);
            mgr.CommitChanges();
        }
    }
}

  在站点上添加默认文档。

AddDefaultDocument
public static void AddDefaultDocument
(
string siteName, string defaultDocName)
{
    
using (ServerManager mgr = new ServerManager())
    {
        Configuration cfg
= mgr.GetWebConfiguration
(siteName);
        ConfigurationSection defaultDocumentSection
= cfg.GetSection("system.webServer/defaultDocument");
        ConfigurationElement filesElement
=
defaultDocumentSection.GetChildElement(
"files");
        ConfigurationElementCollection filesCollection
=
filesElement.GetCollection();

        
foreach (ConfigurationElement elt in filesCollection)
        {
            
if (elt.Attributes["value"].Value.ToString() ==
defaultDocName)
            {
                
return;
            }
        }

        
try
        {
            ConfigurationElement docElement
=
filesCollection.CreateElement();
            docElement.SetAttributeValue(
"value", defaultDocName);
            filesCollection.Add(docElement);
        }
        
catch (Exception) { }   //this will fail if existing

        mgr.CommitChanges();
    }
}
0
相关文章