C#創建IIS之網站或虛擬目錄

来源:互联网 发布:阿尔德里奇数据 编辑:程序博客网 时间:2024/06/08 13:28

IISManager.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.DirectoryServices;
  5. namespace CreaIISvDir
  6. {
  7.     class IISManager
  8.     {
  9.         public IISManager()
  10.         {          
  11.         }
  12.         public static string VirDirSchemaName = "IIsWebVirtualDir";
  13.         private string _serverName;
  14.         
  15.         public string ServerName
  16.         {
  17.             get
  18.             {
  19.                 return _serverName;
  20.             }
  21.             set
  22.             {
  23.                 _serverName = value;
  24.             }
  25.         }
  26.                 
  27.         /// <summary>     
  28.         /// 创建網站或虚拟目录 
  29.         /// </summary>    
  30.         /// <param name="WebSite">服务器站点名称(localhost)</param>    
  31.         /// <param name="VDirName">虚拟目录名称</param>    
  32.         /// <param name="Path">實際路徑</param>     
  33.         /// <param name="RootDir">true=網站;false=虛擬目錄</param>   
  34.         /// <param name="iAuth">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows驗證...更多請查閱MSDN</param>      
  35.         /// <param name="webSiteNum">1</param>     
  36.         /// <param name="serverName">一般為localhost</param> 
  37.         /// <returns></returns> 
  38.         public bool CreateWebSite(string WebSite, string VDirName, string Path, bool RootDir, int iAuth, int webSiteNum, string serverName)     
  39.         {
  40.             try
  41.             {                
  42.                 System.DirectoryServices.DirectoryEntry IISSchema;
  43.                 System.DirectoryServices.DirectoryEntry IISAdmin;
  44.                 System.DirectoryServices.DirectoryEntry VDir;
  45.                 bool IISUnderNT;               
  46.                 
  47.                 
  48.                 //   
  49.                 // 确定IIS版本 
  50.                 //          
  51.                 IISSchema = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/Schema/AppIsolated");
  52.                 if (IISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN")
  53.                     IISUnderNT = true;
  54.                 else
  55.                     IISUnderNT = false;
  56.                 IISSchema.Dispose();
  57.                 //        
  58.                 // Get the admin object         
  59.                 // 获得管理权限       
  60.                 //           
  61.                 IISAdmin = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/W3SVC/" + webSiteNum + "/Root");
  62.                 //          
  63.                 // If we're not creating a root directory        
  64.                 // 如果我们不能创建一个根目录          
  65.                 //              
  66.                 if (!RootDir)
  67.                 {
  68.                     //              
  69.                     // If the virtual directory already exists then delete it            
  70.                     // 如果虚拟目录已经存在则删除    
  71.                     // 
  72.                     foreach (System.DirectoryServices.DirectoryEntry v in IISAdmin.Children)
  73.                     {
  74.                         if (v.Name == VDirName)
  75.                         {
  76.                             // Delete the specified virtual directory if it already exists  
  77.                             try
  78.                             {
  79.                                 IISAdmin.Invoke("Delete"new string[] { v.SchemaClassName, VDirName });
  80.                                 IISAdmin.CommitChanges();
  81.                             }
  82.                             catch (Exception ex)
  83.                             {
  84.                                 throw ex;
  85.                             }
  86.                         }
  87.                     }
  88.                 }
  89.                 //          
  90.                 // Create the virtual directory       
  91.                 // 创建一个虚拟目录       
  92.                 //         
  93.                 if (!RootDir)
  94.                 {
  95.                     VDir = IISAdmin.Children.Add(VDirName, "IIsWebVirtualDir");
  96.                 }
  97.                 else
  98.                 {
  99.                     VDir = IISAdmin;
  100.                 }
  101.                 //         
  102.                 // Make it a web application      
  103.                 // 创建一个web应用        
  104.                 //
  105.                 
  106.                 if (IISUnderNT)
  107.                 {
  108.                     VDir.Invoke("AppCreate"false);
  109.                 }
  110.                 else
  111.                 {
  112.                     VDir.Invoke("AppCreate"true);
  113.                 }
  114.                 
  115.                 //          
  116.                 // Setup the VDir      
  117.                 // 安装虚拟目录      
  118.                 //AppFriendlyName,propertyName,, bool chkRead,bool chkWrite, bool chkExecute, bool chkScript,, true, false, false, true
  119.                 VDir.Properties["AppFriendlyName"][0] = VDirName;    //应用程序名称
  120.                 VDir.Properties["AccessRead"][0] = true//设置读取权限
  121.                 VDir.Properties["AccessExecute"][0] = false;
  122.                 VDir.Properties["AccessWrite"][0] = false;
  123.                 VDir.Properties["AccessScript"][0] = true//执行权限[純腳本]
  124.                 //VDir.Properties["AuthNTLM"][0] = chkAuth;
  125.                 VDir.Properties["EnableDefaultDoc"][0] = true;
  126.                 VDir.Properties["EnableDirBrowsing"][0] = false;
  127.                 VDir.Properties["DefaultDoc"][0] = "Default.aspx,Index.aspx,Index.asp";  //设置默认文档,多值情况下中间用逗号分割
  128.                 VDir.Properties["Path"][0] = Path;
  129.                 VDir.Properties["AuthFlags"][0] = iAuth;
  130.                 //       
  131.                 // NT doesn't support this property     
  132.                 // NT格式不支持这特性      
  133.                 //         
  134.                 if (!IISUnderNT)
  135.                 {
  136.                     VDir.Properties["AspEnableParentPaths"][0] = true;
  137.                 }
  138.                 //   
  139.                 // Set the changes       
  140.                 // 设置改变         
  141.                 //          
  142.                 VDir.CommitChanges();
  143.                 
  144.                 return true;
  145.             }
  146.             catch (Exception ex)
  147.             {
  148.                 throw ex;
  149.             }
  150.         }
  151.         /// <summary>
  152.         /// 獲取VDir支持的所有屬性
  153.         /// </summary>
  154.         /// <returns></returns>
  155.         public string GetVDirPropertyName()
  156.         {
  157.             //System.DirectoryServices.DirectoryEntry VDir;
  158.             const String constIISWebSiteRoot = "IIS://localhost/W3SVC/1/ROOT/iKaoo";
  159.             DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot);
  160.             string sOut = "";
  161.             //下面的方法是得到所有属性名称的方法:
  162.             foreach (PropertyValueCollection pvc in root.Properties)
  163.             {
  164.                 //Console.WriteLine(pvc.PropertyName);
  165.                 sOut += pvc.PropertyName + ":" + pvc.Value.ToString() + "-----------";
  166.             }
  167.             return sOut;
  168.         }
  169.         /// <summary>
  170.         /// 創建虛擬目錄
  171.         /// </summary>
  172.         /// <param name="sDirName">虛擬目錄程式名稱</param>
  173.         /// <param name="sPath">實體路徑</param>
  174.         /// <param name="sDefaultDoc">黙認首頁,多個名稱用逗號分隔</param>
  175.         /// <param name="iAuthFlags">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows驗證...更多請查閱MSDN</param>
  176.         /// <param name="sWebSiteNumber">Win2K,2K3支持多個網站,本次操作哪個網站,黙認網站為1</param>
  177.         /// <returns></returns>
  178.         public bool CreateVDir(string sDirName,string sPath,string sDefaultDoc,int iAuthFlags,string sWebSiteNumber)
  179.         {
  180.             try
  181.             {
  182.                 String sIISWebSiteRoot = "IIS://localhost/W3SVC/" + sWebSiteNumber + "/ROOT";
  183.                 DirectoryEntry root = new DirectoryEntry(sIISWebSiteRoot);
  184.                 foreach (System.DirectoryServices.DirectoryEntry v in root.Children)
  185.                 {
  186.                     if (v.Name == sDirName)
  187.                     {
  188.                         // Delete the specified virtual directory if it already exists  
  189.                         root.Invoke("Delete"new string[] { v.SchemaClassName, sDirName });
  190.                         root.CommitChanges();
  191.                     }
  192.                 }
  193.                 
  194.                 DirectoryEntry tbEntry = root.Children.Add(sDirName, root.SchemaClassName);
  195.                 tbEntry.Properties["Path"][0] = sPath;
  196.                 tbEntry.Invoke("AppCreate"true);
  197.                 //tbEntry.Properties["AccessRead"][0] = true;
  198.                 //tbEntry.Properties["ContentIndexed"][0] = true;
  199.                 tbEntry.Properties["DefaultDoc"][0] = sDefaultDoc;
  200.                 tbEntry.Properties["AppFriendlyName"][0] = sDirName;
  201.                 //tbEntry.Properties["AccessScript"][0] = true;
  202.                 //tbEntry.Properties["DontLog"][0] = true;
  203.                 //tbEntry.Properties["AuthFlags"][0] = 0;
  204.                 tbEntry.Properties["AuthFlags"][0] = iAuthFlags;
  205.                 tbEntry.CommitChanges();
  206.                 return true;
  207.             }
  208.             catch (Exception ex)
  209.             {
  210.                 throw ex;
  211.             }
  212.         }
  213.     }
  214. }

Call it

  1. private void btnCreateIISvDir_Click(object sender, EventArgs e)
  2.         {
  3.             if(new IISManager().CreateWebSite("localhost""Vtest""E://DOC"false, 1, 1, "localhost"))
  4.                 lbInfo.Text = "Create Vtest OK";
  5.         }
  6.         private void btnGetPropertyName_Click(object sender, EventArgs e)
  7.         {
  8.             txtPN.Text = new IISManager().GetVDirPropertyName();
  9.         }
  10.         private void btnCreaVdir_Click(object sender, EventArgs e)
  11.         {
  12.             if (new IISManager().CreateVDir("iKaoo""E://DOC""index.aspx,Default.aspx", 1, "1"))
  13.                 lbInfo.Text = "Create iKaoo OK";
  14.         }