龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

C#操作IIS 7.0详细代码

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
IIS 7.0提供了很多比上一版本(IIS6.0)更多的新特性,包括完全模块化的组件、文本文件的配置功能、MMC图形模式管理工具等等,并且与.NET编程语言结合得更加紧密了,在新添加的Micr

IIS 7.0提供了很多比上一版本(IIS6.0)更多的新特性,包括完全模块化的组件、文本文件的配置功能、MMC图形模式管理工具等等,并且与.NET编程语言结合得更加紧密了,在新添加的Microsoft.Web.Administration名称空间中也增加了很多用于管理和访问IIS的对象,从而使得通过编程方式操作IIS更加简便。虽然在IIS 6.0时代我们也可以非常轻松地通过C#来管理服务器的IIS,但相对来说,现在需要编写的代码更少,所能完成的功能更强。以下是我在曾经做的一个项目中所写的一个类库中的一部分,主要实现了对IIS 7.0的操作,包括创建和删除站点、创建和删除虚拟目录、创建和删除应用程序池、添加站点默认文档、判断站点和虚拟目录是否存在、以及检查Bindings信息等。

    首先是对站点的管理。我写了一个相对较为通用的私有方法,然后在对外的方法中给出了调用接口,包括了创建站点时应用程序池的创建和权限的管理。

CreateSite
/// <summary>
/// Create a new web site.
/// </summary>
/// <param name="siteName"></param>
/// <param name="bindingInfo">"*:&lt;port&gt;:&lt;hostname&gt;" <example>"*:80:myhost.com"</example></param>
/// <param name="physicalPath"></param>
public static void CreateSite(string siteName, string bindingInfo, string physicalPath)
{
    createSite(siteName, "http", bindingInfo, physicalPath, true, siteName + "Pool", ProcessModelIdentityType.NetworkService, null, null, ManagedPipelineMode.Integrated, null);
}

private static void createSite(string siteName, string protocol, string bindingInformation, string physicalPath,
        bool createAppPool, string appPoolName, ProcessModelIdentityType identityType,
        string appPoolUserName, string appPoolPassword, ManagedPipelineMode appPoolPipelineMode, string managedRuntimeVersion)
{
    using (ServerManager mgr = new ServerManager())
    {
        Site site = mgr.Sites.Add(siteName, protocol, bindingInformation, physicalPath);

        // PROVISION APPPOOL IF NEEDED
        if (createAppPool)
        {
            ApplicationPool pool = mgr.ApplicationPools.Add(appPoolName);
            if (pool.ProcessModel.IdentityType != identityType)
            {
                pool.ProcessModel.IdentityType = identityType;
            }
            if (!String.IsNullOrEmpty(appPoolUserName))
            {
                pool.ProcessModel.UserName = appPoolUserName;
                pool.ProcessModel.Password = appPoolPassword;
            }
            if (appPoolPipelineMode != pool.ManagedPipelineMode)
            {
                pool.ManagedPipelineMode = appPoolPipelineMode;
            }

            site.Applications["/"].ApplicationPoolName = pool.Name;
        }

        mgr.CommitChanges();
    }
}
     这个是删除站点的方法,比较简单。

DeleteSite
/// <summary>
/// Delete an existent web site.
/// </summary>
/// <param name="siteName">Site name.</param>
public static void DeleteSite(string siteName)
{
    using (ServerManager mgr = new ServerManager())
    {
        Site site = mgr.Sites[siteName];
        if (site != null)
        {
            mgr.Sites.Remove(site);
            mgr.CommitChanges();
        }
    }
}


精彩图集

赞助商链接