C#中操作IIS 7.0

16 篇文章 0 订阅
13 篇文章 0 订阅

C#中操作IIS 7.0

作者:Jaxu 出处:博客园  2009-3-26 10:17:52 阅读 53  次

<script type="text/javascript"></script>

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

    对于IIS 7.0的介绍读者如果有兴趣的话可以看看下面的两篇文章,我觉得不错!

http://blog.joycode.com/scottgu/archive/2007/04/08/100650.aspx

http://msdn.microsoft.com/en-us/magazine/cc163453.aspx

    不说废话了,赶紧贴代码吧。

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


/// <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();
    }
}

     这个是删除站点的方法,比较简单。


/// <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();
        }
    }
}

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


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();
    }
}

 


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();
            }
        }
    }
}

    删除应用程序池。


/// <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();
        }
    }
}

    在站点上添加默认文档。


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();
    }
}

     检查虚拟目录是否存在。


public static bool VerifyVirtualPathIsExist(string siteName, string path)
{
   
using (ServerManager mgr = new ServerManager())
    {
        Site site
= mgr.Sites[siteName];
       
if (site != null)
        {
           
foreach (Microsoft.Web.Administration.Application app in site.Applications)
            {
               
if (app.Path.ToUpper().Equals(path.ToUpper()))
                {
                   
return true;
                }
            }
        }
    }

   
return false;
}

     检查站点是否存在。


public static bool VerifyWebSiteIsExist(string siteName)
{
   
using (ServerManager mgr = new ServerManager())
    {
       
for (int i = 0; i < mgr.Sites.Count; i++)
        {
           
if (mgr.Sites[i].Name.ToUpper().Equals(siteName.ToUpper()))
            {
               
return true;
            }
        }
    }

   
return false;
}

     检查Bindings信息。


public static bool VerifyWebSiteBindingsIsExist(string bindingInfo)
{
   
string temp = string.Empty;
   
using (ServerManager mgr = new ServerManager())
    {
       
for (int i = 0; i < mgr.Sites.Count; i++)
        {
           
foreach (Microsoft.Web.Administration.Binding b in mgr.Sites[i].Bindings)
            {
                temp
= b.BindingInformation;
               
if (temp.IndexOf('*') < 0)
                {
                    temp
= "*" + temp;
                }
               
if (temp.Equals(bindingInfo))
                {
                   
return true;
                }
            }
        }
    }

   
return false;
}

     以上代码均在Windows Vista SP1和Windows Server 2008上测试通过,使用时需要在工程中引用Microsoft.Web.Administration类库,该类库为IIS 7.0自带的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值