天天看點

使用ADSI實作IIS管理,WEB站點管理系統核心代碼

使用ADSI實作IIS管理,WEB站點管理系統核心代碼
使用ADSI實作IIS管理,WEB站點管理系統核心代碼

代碼

using System; 

using System.Collections.Generic; 

using System.Text; 

using System.IO; 

using System.Collections; 

using System.DirectoryServices; 

using IISMModel; 

using System.Configuration; 

using System.Web; 

namespace IISMBLL 

    /// <summary> 

    /// IIS站點管理器 

    /// </summary> 

    public class IISManager 

    { 

        const string W3SVC_PATH = "IIS://localhost/W3SVC"; 

        // Access Flags 

        const int MD_ACCESS_READ = 0x00000001; //Allow read access. 

        const int MD_ACCESS_SCRIPT = 0x00000200; // Allow script execution. 

        /// <summary> 

        /// 驗證某個虛拟目錄是否存在 

        /// </summary> 

        /// <param name="baseSiteName">虛拟目錄所在的基礎站點</param> 

        /// <param name="virtualDirName">虛拟目錄名</param> 

        /// <returns>存在傳回真,否則傳回假</returns> 

        public Boolean ValidateVirWebSite(string baseSiteName,string virtualDirName) 

        { 

            if (string.IsNullOrEmpty(baseSiteName)) 

            { 

                throw new Exception(IISModel_MSG.IISBLL_IISM_ERROR_VIRDIR_SITE_EMPTY); 

            } 

            if (string.IsNullOrEmpty(virtualDirName)) 

                throw new Exception(IISModel_MSG.IISBLL_IISM_ERROR_VIRDIR); 

            // 站點ID 

            int _WebSiteID = 1; 

            _WebSiteID = GetSiteID(baseSiteName, "localhost"); 

            if (_WebSiteID == 0) 

                throw new Exception(IISModel_MSG.IISBLL_IISM_ERROR_VIRDIR_SITE_NOTFOUND); 

            String siteRoot = "IIS://localhost/W3SVC/" + _WebSiteID.ToString() + "/ROOT"; 

            DirectoryEntry root = new DirectoryEntry(siteRoot); 

            foreach (DirectoryEntry child in root.Children) 

                if (child.Name.ToLower() == virtualDirName) 

                { 

                    return true; 

                } 

            return false; 

        } 

        /// 驗證某個站點是否存在 

        /// <param name="siteName"></param> 

        /// <returns></returns> 

        public Boolean ValidateWebSite(string siteName) 

            return 

                GetSiteID(siteName, "localhost")>0; 

        /// 在主機上建立虛拟目錄 

        public void CreateVirWebSite(string _virtualDirName, string _physicalPath) 

            try 

                // 站點ID 

                int _WebSiteID = 1; 

                //得到預設站點 

                _WebSiteID = GetSiteID(ConfigurationManager.AppSettings["defaultSite"], "localhost"); 

                if (_WebSiteID == 0) 

                    _WebSiteID = 1; 

                if (string.IsNullOrEmpty(_virtualDirName)) 

                    throw new NullReferenceException("建立虛拟目錄名不能為空"); 

                String constIISWebSiteRoot = "IIS://localhost/W3SVC/" + _WebSiteID.ToString() + "/ROOT"; 

                string virtualDirName = _virtualDirName; //虛拟目錄名稱:Monitor 

                string physicalPath = _physicalPath; //虛拟目錄實體路徑 

                if (String.IsNullOrEmpty(physicalPath)) 

                    throw new NullReferenceException("建立虛拟目錄的實體路徑不能為空"); 

                DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot); 

                // 如果虛拟目錄存在則删除 

                foreach (System.DirectoryServices.DirectoryEntry v in root.Children) 

                    if (v.Name == _virtualDirName) 

                    { 

                        // Delete the specified virtual directory if it already exists 

                        try 

                        { 

                            root.Invoke("Delete", new string[] { v.SchemaClassName, _virtualDirName }); 

                            root.CommitChanges(); 

                        } 

                        catch 

                            throw;                             

                    } 

                DirectoryEntry tbEntry = root.Children.Add(virtualDirName, "IIsWebVirtualDir"); 

                tbEntry.Properties["Path"][0] = physicalPath;  //虛拟目錄實體路徑 

                tbEntry.Invoke("AppCreate", true); 

                tbEntry.Properties["AccessRead"][0] = true;   //設定讀取權限 

                tbEntry.Properties["ContentIndexed"][0] = true; 

                tbEntry.Properties["DefaultDoc"][0] = "index.aspx,Default.aspx"; //設定預設文檔,多值情況下中間用逗号分割 

                tbEntry.Properties["AppFriendlyName"][0] = virtualDirName; //虛拟目錄名稱:Monitor 

                tbEntry.Properties["AccessScript"][0] = true; //執行權限 

                tbEntry.Properties["AppIsolated"][0] = "1"; 

                tbEntry.Properties["DontLog"][0] = true;  // 是否記錄日志                 

                tbEntry.Properties["AuthFlags"][0] = 1;// 設定目錄的安全性,0表示不允許匿名通路,1為允許,3為基本身份驗證,7為windows繼承身份驗證 

                tbEntry.CommitChanges(); 

                // 增加MIME 的類型:flv 

                //SetMimeTypeProperty(constIISWebSiteRoot, ".flv", "flv"); 

                // 修改IIS屬性 

                //SetSingleProperty("IIS://localhost/W3SVC/" + _WebSiteID.ToString(), "ServerBindings", ":8080:"); 

                ////得到現預設站點的IP 端口 描述        

                //string strServerBindings = root.Properties["ServerBindings"].Value.ToString(); 

                ////解出端口Port 

                //string[] strArr = strServerBindings.Split(':'); 

                ////重新指派為8080 

                //root.Properties["ServerBindings"].Value = strArr[0] + ":8080:" + strArr[2]; 

                root.CommitChanges();//确認更改 

            catch 

        /// 删除Web虛拟目錄 

        /// <param name="_virtualDirName"></param> 

        public void RemoveVirWebSite(string _virtualDirName) 

            //得到預設站點 

            _WebSiteID = GetSiteID(ConfigurationManager.AppSettings["defaultSite"], "localhost"); 

                _WebSiteID = 1; 

            if (string.IsNullOrEmpty(_virtualDirName)) 

                throw new NullReferenceException("建立虛拟目錄名不能為空"); 

            String constIISWebSiteRoot = "IIS://localhost/W3SVC/" + _WebSiteID.ToString() + "/ROOT"; 

            string virtualDirName = _virtualDirName; //虛拟目錄名稱:Monitor 

            using (DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot)) 

                        root.Invoke("Delete", new string[] { v.SchemaClassName, _virtualDirName }); 

                        root.CommitChanges(); 

                        break; 

                root.Close();  

        /// 建立獨立的Web站點 

        /// <param name="realPath"></param> 

        public void CreateWebSite(string siteName, string realPath) 

            if (string.IsNullOrEmpty(siteName)) 

                throw new NullReferenceException("建立站點的站點名字不能為空"); 

            if (string.IsNullOrEmpty(realPath)) 

                throw new NullReferenceException("建立站點的站點真是路徑不能為空"); 

            DirectoryEntry root = new DirectoryEntry(W3SVC_PATH); 

            //判斷站點是否已經存在,如果存在,則删除已有站點 

            int siteID = GetSiteID(siteName, "localhost"); 

            if (siteID > 0) 

                throw new Exception("要建立的站點已經存在"); 

            siteID = getNewWebSiteID(); 

            DirectoryEntry currentWeb = 

                root.Children.Add(siteID.ToString(), "IIsWebServer"); 

            currentWeb.CommitChanges(); 

            //currentWeb.Properties["Location"].Value = "/LM/W3SVC/" + siteID.ToString(); 

            currentWeb.Properties["AuthFlags"][0] = "0"; 

            currentWeb.Properties["MaxBandwidth"][0] = "1048576"; 

            currentWeb.Properties["MaxConnections"][0] = "10"; 

            currentWeb.Properties["ServerAutoStart"][0] = "true"; 

            currentWeb.Properties["ServerBindings"].Value = ":80:" + siteName; 

            currentWeb.Properties["ServerComment"][0] = siteName; 

            // 添加web虛拟目錄 

            DirectoryEntry virEntry = currentWeb.Children.Add("root","IIsWebVirtualDir"); 

            virEntry.CommitChanges(); 

            //virEntry.Properties["Location"].Value = "/LM/W3SVC/"+siteID.ToString()+"/root"; 

            virEntry.Properties["AccessFlags"][0] = MD_ACCESS_READ | MD_ACCESS_SCRIPT; 

            virEntry.Properties["AppFriendlyName"][0] = siteName; 

            virEntry.Properties["AppIsolated"][0] = "2"; 

            virEntry.Properties["AppRoot"][0] = "/LM/W3SVC/" + siteID.ToString() + "/Root"; 

            virEntry.Properties["AuthFlags"][0] = 1 | 7;// 設定目錄的安全性,0表示不允許匿名通路,1為允許,3為基本身份驗證,7為windows繼承身份驗證             

            virEntry.Properties["Path"][0] = realPath;  //虛拟目錄實體路徑 

            virEntry.Close(); 

            currentWeb.Close(); 

            root.Close(); 

        /// 删除Web站點 

        public void RemoveWebSite(string siteName) 

            using (DirectoryEntry root = new DirectoryEntry(W3SVC_PATH)) 

                foreach (DirectoryEntry Child in root.Children) 

                    if (Child.SchemaClassName == "IIsWebServer") 

                        string WName = Child.Properties["ServerComment"][0].ToString(); 

                        if (siteName.ToLower() == WName.ToLower()) 

                            Child.DeleteTree(); 

                            break; 

                        }   

                root.Close(); 

        /// 得到新的站點ID 

        private int getNewWebSiteID() 

           using(System.DirectoryServices.DirectoryEntry rootEntry =  

               new System.DirectoryServices.DirectoryEntry(W3SVC_PATH)) 

           { 

               int siteID = 1; 

               //得到現有的站點辨別 

               foreach (System.DirectoryServices.DirectoryEntry entry in rootEntry.Children) 

               { 

                   if (entry.SchemaClassName == "IIsWebServer") 

                   { 

                       int ID = Convert.ToInt32(entry.Name); 

                       if (ID >= siteID) 

                       { 

                           siteID = ID + 1; 

                       } 

                   } 

               } 

               rootEntry.Close(); 

               return siteID; 

           } 

        #region 根據站點名稱擷取站點ID(辨別) 

        /// 根據站點名稱擷取站點ID(辨別) 

        /// <param name="webSiteName">站點名稱</param> 

        /// <param name="serverIP">主機IP</param> 

        /// <returns>站點ID</returns> 

        private int GetSiteID(string webSiteName, string serverIP) 

            int SiteID = 0; 

                DirectoryEntry root = new DirectoryEntry(@"IIS://" + serverIP + "/W3SVC");                 

                {                     

                    string WName = Child.Properties["ServerComment"][0].ToString(); 

                    if (webSiteName == WName) 

                    {                         

                        SiteID = Convert.ToInt32(Child.Name); 

                        return SiteID; 

                    WName = ""; 

                SiteID = 0; 

            return SiteID; 

        #endregion 

        /// 設定IIS的MIME類型,SetMimeTypeProperty("IIS://localhost/W3SVC/1/Root", ".hlp", "application/winhlp"); 

        /// <param name="metabasePath"></param> 

        /// <param name="newExtension"></param> 

        /// <param name="newMimeType"></param> 

        static void SetMimeTypeProperty(string metabasePath, string newExtension, string newMimeType) 

            //  metabasePath is of the form "IIS://<servername>/<path>" 

            //    for example "IIS://localhost/W3SVC/1/Root"  

            //  newExtension is of the form ".<extension>", for example, ".hlp" 

            //  newMimeType is of the form "<application>", for example, "application/winhlp" 

            Console.WriteLine("\nAdding {1}->{2} to the MimeMap property at {0}:", metabasePath, newExtension, newMimeType); 

                DirectoryEntry path = new DirectoryEntry(metabasePath); 

                PropertyValueCollection propValues = path.Properties["MimeMap"]; 

                Console.WriteLine(" Old value of MimeMap has {0} elements", propValues.Count); 

                object exists = null; 

                foreach (object value in propValues) 

                    // IISOle requires a reference to the Active DS IIS Namespace Provider in Visual Studio .NET 

                    IISOle.IISMimeType mimetypeObj = (IISOle.IISMimeType)value; 

                    Console.WriteLine("  {0}->{1}", mimetypeObj.Extension, mimetypeObj.MimeType); 

                    if (newExtension == mimetypeObj.Extension) 

                        exists = value; 

                if (null != exists) 

                    propValues.Remove(exists); 

                    Console.WriteLine(" Found an entry for {0}; removing it before adding the new one.", newExtension); 

                IISOle.MimeMapClass newObj = new IISOle.MimeMapClass(); 

                newObj.Extension = newExtension; 

                newObj.MimeType = newMimeType; 

                propValues.Add(newObj); 

                path.CommitChanges(); 

                Console.WriteLine(" Done."); 

            catch (Exception ex) 

                if ("HRESULT 0x80005006" == ex.Message) 

                    Console.WriteLine(" Property MimeMap does not exist at {0}", metabasePath); 

                else 

                    Console.WriteLine("Failed in SetMimeTypeProperty with the following exception: \n{0}", ex.Message); 

        /// 修改IIS屬性 

        /// <param name="propertyName"></param> 

        /// <param name="newValue"></param> 

        static void SetSingleProperty(string metabasePath, string propertyName, object newValue) 

            //    for example "IIS://localhost/W3SVC/1"  

            //  propertyName is of the form "<propertyName>", for example "ServerBindings" 

            //  value is of the form "<intStringOrBool>", for example, ":80:" 

            Console.WriteLine("\nSetting single property at {0}/{1} to {2} ({3}):", 

                metabasePath, propertyName, newValue, newValue.GetType().ToString()); 

                PropertyValueCollection propValues = path.Properties[propertyName]; 

                string oldType = propValues.Value.GetType().ToString(); 

                string newType = newValue.GetType().ToString(); 

                Console.WriteLine(" Old value of {0} is {1} ({2})", propertyName, propValues.Value, oldType); 

                if (newType == oldType) 

                    path.Properties[propertyName][0] = newValue; 

                    path.CommitChanges(); 

                    Console.WriteLine("Done"); 

                    Console.WriteLine(" Failed in SetSingleProperty; type of new value does not match property"); 

                    Console.WriteLine(" Property {0} does not exist at {1}", propertyName, metabasePath); 

                    Console.WriteLine("Failed in SetSingleProperty with the following exception: \n{0}", ex.Message); 

        /// 建立FTP虛拟目錄 

        /// <param name="virDirName"></param> 

        public void CreateFTPVirDir(string virDirName,string realPath) 

              string   strSchema=   "IIsFtpVirtualDir";    

              string   strRootSubPath   =   "/MSFTPSVC/1/Root"; 

              string FtpName = virDirName; 

              string DirName = realPath;    

              DirectoryEntry   deRoot=   new   DirectoryEntry("IIS://localhost"+   strRootSubPath); 

              try 

              { 

                  deRoot.RefreshCache();    

                  DirectoryEntry   deNewVDir   =   deRoot.Children.Add(FtpName,strSchema);    

                  //deNewVDir.Properties["Path"].Insert(0,DirName); 

                  deNewVDir.Properties["Path"][0] = DirName; 

                  deNewVDir.Properties["AccessRead"][0] = true; 

                  deNewVDir.Properties["AccessWrite"][0] = true; 

                  deNewVDir.CommitChanges();    

                  deRoot.CommitChanges();                    

                  deNewVDir.Close();    

                  deRoot.Close();    

              } 

              catch (Exception) 

                  throw; 

        /// 删除FTP虛拟目錄 

        public void RemoveFTPVirDir(string virDirName) 

            string strSchema = "IIsFtpVirtualDir"; 

            string strRootSubPath = "/MSFTPSVC/1/Root"; 

            string FtpName = virDirName; 

            using (DirectoryEntry root = new DirectoryEntry("IIS://localhost" + strRootSubPath)) 

                root.RefreshCache(); 

                //如果虛拟目錄存在則删除 

                foreach (DirectoryEntry item in root.Children) 

                    if (item.Name == virDirName) 

                        root.Invoke("Delete", new string[] { strSchema, virDirName }); 

        public string GetBaseUrl(HttpContext context) 

                context.Request.Url.Scheme + "://" + 

                context.Request.Url.Authority +  

                context.Request.ApplicationPath; 

    } 

繼續閱讀