C#操作IIS服務


進入正題:先從使用角度來講解IIS操作,然后再深入到具體的IIS服務底層原理。

【1】前提掌握要點:

(1)、IIS到目前經歷了四個版本分別為 IIS4.0 IIS5.0 IIS6.0 IIS7.0,其中IIS6.0 IIS7.0是在5.0的安全問題的基礎上獲得的發展,目前為止。6.0版本以后的都是比較安全穩定的,為什么需要了解IIS版本,是因為6.0以后和之前的IIS提供的操作API是不一樣的,不過IIS6.0時代主要以using System.DirectoryServices空間下的DirectoryEntry 對象作為編程訪問一個主要載體.但隨着IIS7.0發布.NET的Web程序由IIS6.0開始逐漸過渡到 7.0版本.而且在編程控制IIS上新添加的Microsoft.Web.Administration名稱空間, 可以操作7.0

(2)、平時的站點部署需要配置什么參數或者說是我們一般自己部署站點需要什么場景的操作,考慮可以用程序實現的,然后可以模型化為對象去實現。

我采用的方案是:將部署的站點聲明為一個對象,其中包含了一般我們站點部署時設置的參數作為它的屬性和字段,將我們一般站點設置實現為一些方法。

可以先定義一個站點類:

 

 
//站點身份驗證模式
public enum autherRight {asp_net模擬, Form身份驗證, Windows身份驗證, 基本身份驗證,匿名身份驗證,摘要式身份驗證 };
/// <summary>
/// 站點類
/// </summary>
public class newWebSiteInfo
{
     //站點設置參數
     public string hostIp;  //主機ip
     public string porNum;  //端口號
     public string hostName; //主機名
     public string webName; //網站名
     public string appName; //應用程序池
     public string webPath; //根目錄
     public string visualPath; //虛擬目錄
     public Dictionary< string , string > newMimeType; //需要新添加mime類型
     public autherRight autherRight; //身份驗證模式
     public string defoultPage; //默認文檔
 
     public newWebSiteInfo( string hostip, string portnum, string hostname, string webname, string appName, string webpath, string visualPath, Dictionary< string , string > newMimeType, autherRight autherRight, string defoultPage)
     {
         this .hostIp = hostip;
         this .porNum = portnum;
         this .hostName = hostname;
         this .webName=webname;
         this .appName = appName;
         this .webPath = webpath;
         this .visualPath = visualPath;
         this .newMimeType = newMimeType;
         this .autherRight = autherRight;
         this .defoultPage = defoultPage;
     }
     /// <summary>
     /// 返回站點綁定信息
     /// </summary>
     /// <returns></returns>
     public string bindString()
     {
             return String.IsNullOrEmpty(hostName) ? String.Format( "http://{0}:{1}" , hostIp, porNum) : String.Format( "http://{0}:{1}" , hostName, porNum);
     }
}

目前IIS操作主要有兩種方式:一種是System.DirectoryServices空間下面的類,用於IIS5/6版本,和可以兼容iis6的IIS7版本;Microsoft.Web.Administration空間下面的類,IIS7引入的新的管理類,主要通過ServerManger類進行站點新增。

本次主要通過System.DirectoryServices方式操作IIS,也簡要介紹一下ServerManger新建站點:

(1) 添加.net引用Microsoft.Web.Administration.dll,實例化ServerManger新增站點方式如下:

 
using System;
using Microsoft.Web.Administration;
 
class CreateASite
{
     static void Main( string [] args)
     {
         ServerManager serverManager = new ServerManager();
         Site mySite = serverManager.Sites.Add(
             "MySite" , "d:\\inetpub\\mysite" , 8080);
         mySite.ServerAutoStart = true ;
         serverManager.CommitChanges();
     }
}

(2)通過System.DirectoryServices空間下面的類獲取IIS服務,但其實對於高版本的也可以同時引用Microsoft.Web.Administration.dll中通過ServerManger來進行參數設置各有各的好處。

首先介紹一下我用到的幾個命名空間:

 
using System.DirectoryServices;  //獲取目錄實體類
using Microsoft.Web.Administration; //ServerManger類所屬命名空間using IISOle;                      //IIS管理添加mime類型
using System.Security.AccessControl; //設置文件安全權限類所屬命名空間
using System.IO;                    //文件路徑類所屬命名空間
using System.ServiceProcess;        //上一節中所用的系統服務對象所屬命名空間

現在提供我自己的源代碼,可以適用一般類需求,對於一些特殊配置的應用程序部署,可以稍微做微調。

 
///created by george
///date:2014-5-3
///QQ:709617880
namespace IISmng
     //站點身份驗證模式
     public enum autherRight {asp_net模擬, Form身份驗證, Windows身份驗證, 基本身份驗證,匿名身份驗證,摘要式身份驗證 };
     /// <summary>
     /// 站點類
     /// </summary>
     public class newWebSiteInfo
     {
         //站點設置參數
         public string hostIp;  //主機ip
         public string porNum;  //端口號
         public string hostName; //主機名
         public string webName; //網站名
         public string appName; //應用程序池
         public string webPath; //物理路徑
         public string visualPath; //虛擬目錄
         public Dictionary< string , string > newMimeType; //需要新添加mime類型
         public autherRight autherRight; //身份驗證模式
         public string defoultPage; //默認文檔
 
         public newWebSiteInfo( string hostip, string portnum, string hostname, string webname, string appName, string webpath, string visualPath, Dictionary< string , string > newMimeType, autherRight autherRight, string defoultPage)
         {
             this .hostIp = hostip;
             this .porNum = portnum;
             this .hostName = hostname;
             this .webName=webname;
             this .appName = appName;
             this .webPath = webpath;
             this .visualPath = visualPath;
             this .newMimeType = newMimeType;
             this .autherRight = autherRight;
             this .defoultPage = defoultPage;
         }
         /// <summary>
         /// 返回站點綁定信息
         /// </summary>
         /// <returns></returns>
         public string bindString()
         {
                 return String.IsNullOrEmpty(hostName) ? String.Format( "http://{0}:{1}" , hostIp, porNum) : String.Format( "http://{0}:{1}" , hostName, porNum);
         }
     }
     //托管模式
     public enum modelType{集成,經典};
     //net版本
     public enum netVersion{ v2_0 , v4_0};
     /// <summary>
     /// IIS操作類
     /// </summary>
     public class myIIS
    
         /// <summary>
         /// IIS版本屬性
         /// </summary>
         public String IISVersion {
 
             get { return IISVersion; }
 
             set {
               DirectoryEntry IISService = new DirectoryEntry( "IIS://localhost/W3SVC/INFO" );
               IISVersion = "v" +IISService.Properties[ "MajorIISVersionNumber" ].Value.ToString();
             }
         
         }
 
         /// <summary>
         /// 檢測客戶端或服務器是否安裝IIS服務
         /// </summary>
         /// <returns>true OR false</returns>
         public Boolean checkIIS() {
             Boolean retMsg = false ;
             try {
                  DirectoryEntry IISService = new DirectoryEntry( "IIS://localhost/W3SVC" );
                  if (IISService.GetType().ToString().Equals( "DirectoryEntry" ))
                  {
                      if (checkServiceIsRunning( "IIS Admin Service" ))
                             retMsg= true ;
                  }
             }
             catch (Exception e){
 
             }
             return retMsg;
         }
 
         /// <summary>
         /// 檢測服務是否開啟
         /// </summary>
         /// <param name="serviceName"></param>
         /// <returns></returns>
         public Boolean checkServiceIsRunning( string serviceName)
         {
             ServiceController[] allServices = System.ServiceProcess.ServiceController.GetServices();
             Boolean runing = false ;
             foreach (ServiceController sc in allServices)
             {
                 if (sc.DisplayName.Trim() == serviceName.Trim())
                 {
                     if (sc.Status.ToString() == "Running" )
                     {
                         runing = true ;
                     }
                 }
             }
             return runing;
         }
         /// <summary>
         /// 獲取本機IIS版本
         /// </summary>
         /// <returns></returns>
         public String getIISVersion() {
             String retStr = "" ;
             if (checkIIS())
             {
                 DirectoryEntry IISService = new DirectoryEntry( "IIS://localhost/W3SVC/INFO" );
                  retStr = "v" +IISService.Properties[ "MajorIISVersionNumber" ].Value.ToString();
             }
             return retStr;
         }
 
         /// <summary>
         /// 判斷程序池是否存在
         /// </summary>
         /// <param name="AppPoolName">程序池名稱</param>
         /// <returns>true存在 false不存在</returns>
         private bool isAppPoolExist( string AppPoolName)
         {
             bool result = false ;
             DirectoryEntry appPools = new DirectoryEntry( "IIS://localhost/W3SVC/AppPools" );
             foreach (DirectoryEntry appPool in appPools.Children)
             {
                 if (appPool.Name.Equals(AppPoolName))
                 {
                     result = true ;
                 }
             }
             return result;
         }
 
         /// <summary>
         /// 創建應用程序池
         /// </summary>
         /// <param name="appName">自定義引用程序池名</param>
         /// <param name="type">托管類型</param>
         /// <param name="netV">.net版本</param>
         /// <returns></returns>
         public DirectoryEntry creatAppPool( string appName, modelType type, netVersion netV)
         {
 
             if (!isAppPoolExist(appName))
             {
                 DirectoryEntry newpool;
                 DirectoryEntry appPools = new DirectoryEntry( "IIS://localhost/W3SVC/AppPools" );
                 newpool = appPools.Children.Add(appName, "IIsApplicationPool" );
                 //修改應用程序池配置
                 setModalAndNetVersionOfappPool(appName, type, netV);
                 newpool.CommitChanges();
                 return newpool;
             }
             else return null ;
 
         }
 
         /// <summary>
         /// 刪除指定程序池
         /// </summary>
         /// <param name="AppPoolName">程序池名稱</param>
         /// <returns>true刪除成功 false刪除失敗</returns>
         private bool deleteAppPool( string AppPoolName)
         {
             bool result = false ;
             if (isAppPoolExist(AppPoolName)) return result;
             DirectoryEntry appPools = new DirectoryEntry( "IIS://localhost/W3SVC/AppPools" );
             foreach (DirectoryEntry appPool in appPools.Children)
             {
                 if (appPool.Name.Equals(AppPoolName))
                 {
                     try
                     {
                         appPool.DeleteTree();
                         result = true ;
                     }
                     catch
                     {
                         result = false ;
                     }
                 }
             }
             return result;
         }
 
         /// <summary>
         /// 設置應用程序池的托管模式和.net版本
         /// </summary>
         /// <param name="appPoolName"></param>
         /// <param name="modelType"></param>
         /// <param name="netVersion"></param>
         public void setModalAndNetVersionOfappPool( string appPoolName, modelType mt, netVersion nv) {
             if (String.IsNullOrEmpty(appPoolName)) return ;
             if (isAppPoolExist(appPoolName)) return ;
             if (nv == null ) return ;
             if (mt == null ) return ;
             ServerManager sm = new ServerManager();
             if (nv == netVersion.v2_0)
             {
                 sm.ApplicationPools[appPoolName].ManagedRuntimeVersion = "v2.0" ;
             }
             else if (nv == netVersion.v4_0) {
 
                 sm.ApplicationPools[appPoolName].ManagedRuntimeVersion = "v4.0" ;
             }
 
             if (mt == modelType.集成)
             {
                 sm.ApplicationPools[appPoolName].ManagedPipelineMode = ManagedPipelineMode.Integrated;
             }
             else if (mt==modelType.經典)
             {
                 sm.ApplicationPools[appPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated為集成 Classic為經典
             }
             sm.CommitChanges();
 
         }
 
         /// <summary>
         ///檢測網站名是否可用
         /// </summary>
         /// <param name="siteInfo"></param>
         /// <returns>true 可用,false 不可用過</returns>
         public bool checkWebNameIsAvailble( string webComment)
         {
             //檢測網站名是否可用
             bool isAvalable = true ;
             DirectoryEntry serviceEntry = new DirectoryEntry( "IIS://localhost/W3SVC" );
             foreach (DirectoryEntry entry in serviceEntry.Children)
             {
                 if (entry.SchemaClassName == "IIsWebServer" )
                 {
                     string webName = entry.Properties[ "ServerComment" ].Value.ToString();
 
                     if (webName == webComment)
                     {
                         isAvalable = false ;
                         break ;
                     }
                 }
             }
             return isAvalable;
         }
 
         /// <summary>
         /// 檢測端口號是否已被占用
         /// 注意:端口號輸入有限制,在調用該方法前,需要做端口號合理性校驗
         /// </summary>
         /// <param name="portNum"></param>
         /// <returns></returns>
         public bool checkPortIsVailble( string portNum) {
             bool isVailble = true ;
             DirectoryEntry serviceEntry = new DirectoryEntry( "IIS://localhost/W3SVC" );
             foreach (DirectoryEntry entry in serviceEntry.Children)
             {
                 if (entry.SchemaClassName == "IIsWebServer" )
                 {
                     if (entry.Properties[ "ServerBindings" ].Value != null )
                     {
                         string Binding = entry.Properties[ "ServerBindings" ].Value.ToString().Trim();
                         string [] Info = Binding.Split( ':' );
                         if (Info[1].Trim() == portNum)
                         {
                             isVailble = false ;
                             break ;
                         }
                     }
                 }
 
             }
             return isVailble;
         }
        
         /// <summary>
         /// 創建網站
         /// </summary>
         /// <param name="siteInfo"></param>
         public DirectoryEntry creatNewWeb(newWebSiteInfo siteInfo,modelType type,netVersion netV)
         {
            
             DirectoryEntry Services = new DirectoryEntry( "IIS://localhost/W3SVC" );
             int webID = 0;
             foreach (DirectoryEntry server in Services.Children)
             {
                 if (server.SchemaClassName == "IIsWebServer" )
                 {
                     if (Convert.ToInt32(server.Name) > webID)
                     {
                         webID = Convert.ToInt32(server.Name);
                     }
                 }
             }
             webID++;
 
             //創建站點
             DirectoryEntry mySitServer = Services.Children.Add(webID.ToString(), "IIsWebServer" );
             mySitServer.Properties[ "ServerComment" ].Clear();
             mySitServer.Properties[ "ServerComment" ].Add(siteInfo.webName);
             mySitServer.Properties[ "Serverbindings" ].Clear();
             mySitServer.Properties[ "Serverbindings" ].Add( ":" + siteInfo.porNum + ":" );
             mySitServer.Properties[ "Path" ].Clear(); //注意該path為站點的路徑,新增站點時,兩者目錄一致
             mySitServer.Properties[ "path" ].Add(siteInfo.webPath);
             mySitServer.Properties[ "DefaultDoc" ].Add(siteInfo.defoultPage); //設置默認文檔
            
             //創建虛擬目錄
             DirectoryEntry root = mySitServer.Children.Add( "Root" , "IIsWebVirtualDir" );
             root.Properties[ "path" ].Clear(); //該路勁屬性是站點下虛擬路徑的路徑,類似於站點的子路徑
             root.Properties[ "path" ].Add(siteInfo.visualPath);
 
            
             if ( string .IsNullOrEmpty(siteInfo.appName))
             {
                 root.Invoke( "appCreate" , 0);
             }
             else
             {
                 
                 //創建引用程序池
                 string appPoolName = siteInfo.appName;
                 if (!isAppPoolExist(appPoolName))
                 {
                     DirectoryEntry newpool;
                     DirectoryEntry appPools = new DirectoryEntry( "IIS://localhost/W3SVC/AppPools" );
                     newpool = appPools.Children.Add(appPoolName, "IIsApplicationPool" );
                     newpool.CommitChanges();
 
                 }
                 //修改應用程序池配置
                 setModalAndNetVersionOfappPool(appPoolName, type,netV);
                 root.Invoke( "appCreate3" , 0, appPoolName, true );
             }
             
             root.Properties[ "AppFriendlyName" ].Clear();
             root.Properties[ "AppIsolated" ].Clear();
             root.Properties[ "AccessFlags" ].Clear();
             root.Properties[ "FrontPageWeb" ].Clear();
             root.Properties[ "AppFriendlyName" ].Add(root.Name);
             root.Properties[ "AppIsolated" ].Add(2);
             root.Properties[ "AccessFlags" ].Add(513);
             root.Properties[ "FrontPageWeb" ].Add(1);
 
             root.CommitChanges();
             mySitServer.CommitChanges();
 
             return mySitServer;
 
         }
         /// <summary>
         /// 設置站點新增自定義mime類型,一次添加一個類型
         /// </summary>
         /// <param name="siteInfo"></param>
         /// <param name="mysiteServer"></param>
         public void addMIMEtype(newWebSiteInfo siteInfo,DirectoryEntry mysiteServer)
         {
             //需要添加新的mime類型
             if (siteInfo.newMimeType.Count > 0)
             {
                 IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
                 NewMime.Extension = siteInfo.newMimeType.Keys.ToString(); NewMime.MimeType = siteInfo.newMimeType.Values.ToString();
                 IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
                 mysiteServer.Properties[ "MimeMap" ].Add(NewMime);
                 mysiteServer.CommitChanges();
             }
 
         }
 
         /// <summary>
         /// 設置文件夾權限 處理給EVERONE賦予所有權限
         /// </summary>
         /// <param name="FileAdd">文件夾路徑</param>
         public void SetFileRole(newWebSiteInfo siteInfo)
         {
             DirectoryInfo dir_info = new DirectoryInfo(siteInfo.webPath);
             DirectorySecurity dir_security = new DirectorySecurity();
             dir_security.AddAccessRule( new FileSystemAccessRule( "Everyone " , FileSystemRights.WriteData, AccessControlType.Allow));
             dir_info.SetAccessControl(dir_security);
         }
 
         /// <summary>
         /// 刪除網站
         /// </summary>
         /// <param name="webName"></param>
         public void deletWeb( string webName) {
             DirectoryEntry Services = new DirectoryEntry( "IIS://localhost/W3SVC" );
             foreach (DirectoryEntry server in Services.Children)
             {
                 if (server.SchemaClassName == "IIsWebServer" )
                 {
                     if (server.Properties[ "ServerComment" ].Value == webName || server.Name==webName)
                     {
                         server.DeleteTree();
                         break ;
                     }
                 }
             }
 
             Services.CommitChanges();
         }
     }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM