在当前站点下面创建(删除)应用程序

时间:2021-01-12 08:10:37
         /// <summary>
        /// 在IIS子站点下面创建应用程序并且创建虚拟目录
        /// </summary>
        /// <param name="appPoolName">需要创建的应用程序名称</param>
        /// <param name="Path">路径</param>
        /// <param name="Id">站点siteId</param>
        /// <returns></returns>
        public static void CreateAppPool(string appPoolName, string path, string id)
        {
            var entPath = "IIS://localhost/w3svc";
            DirectoryEntry rootfolder = new DirectoryEntry(entPath);
            DirectoryEntry root = new DirectoryEntry(entPath + "/" + id + "/ROOT");
            DirectoryEntry siteVDir = root.Children.Add(appPoolName, "IISWebVirtualDir");
            siteVDir.Properties["AppIsolated"][0] = 2;
            siteVDir.Properties["Path"][0] = path;
            siteVDir.Properties["AccessFlags"][0] = 513;
            siteVDir.Properties["FrontPageWeb"][0] = 1;
            siteVDir.Properties["AppFriendlyName"][0] = appPoolName;
            siteVDir.CommitChanges();
        }
        
        /// <summary>
        /// 删除IIS站点下面的应用程序
        /// </summary>
        /// <param name="SiteID">站点Id</param>
        /// <param name="appPoolName">虚拟目录(应用程序)</param>
        /// <returns></returns>
        public static bool DeletedDir(string appPoolName, string siteId)
        {
            var IISAdmin = new System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/" + siteId + "/Root");
            foreach (System.DirectoryServices.DirectoryEntry v in IISAdmin.Children)
            {
                if (v.Name == appPoolName)
                {
                    try
                    {
                        IISAdmin.Invoke("Delete", new string[] { v.SchemaClassName, appPoolName });
                        IISAdmin.CommitChanges();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
            return false;
        }