【C#】通过C#代码创建IIS应用程序池和网站

代码

参考了其他人的代码,做了一些优化,很多代码用不上

    /// 
    /// IIS 操作方法集合
    /// 
    public class IISWorker
    {
        private static string HostName = "localhost";

        /// 
        /// 获取本地IIS版本
        /// 
        /// 
        public static string GetIIsVersion()
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry("IIS://" + HostName + "/W3SVC/INFO");
                string version = entry.Properties["MajorIISVersionNumber"].Value.ToString();
                return version;
            }
            catch (Exception se)
            {
                //说明一点:IIS5.0中没有(int)entry.Properties["MajorIISVersionNumber"].Value;属性,将抛出异常 证明版本为 5.0
                return string.Empty;
            }
        }

        /// 
        /// 创建虚拟目录网站
        /// 
        /// 网站名称
        /// 物理路径
        /// 站点+端口,如192.168.1.23:90
        /// 是否创建新的应用程序池
        /// 
        public static int CreateWebSite(string webSiteName, string physicalPath, string domainPort)
        {
            DirectoryEntry root = new DirectoryEntry("IIS://" + HostName + "/W3SVC");
            // 为新WEB站点查找一个未使用的ID
            int siteID = 1;
            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {
                    int ID = Convert.ToInt32(e.Name);
                    if (ID >= siteID) { siteID = ID + 1; }
                }
            }

            //需先删除旧网站
            DeleteWebsite(webSiteName);

            DirectoryEntry apppools2 = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");
            //删除原应用程序池
            foreach (DirectoryEntry a in apppools2.Children)
            {
                if (a.Name == webSiteName)
                {
                    apppools2.Children.Remove(a);
                    apppools2.CommitChanges();
                }
            }

            // 创建WEB站点
            DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
            site.Invoke("Put", "ServerComment", webSiteName);
            site.Invoke("Put", "KeyType", "IIsWebServer");
            site.Invoke("Put", "ServerBindings", domainPort + ":");
            site.Invoke("Put", "ServerState", 2);
            site.Invoke("Put", "FrontPageWeb", 1);
            site.Invoke("Put", "DefaultDoc", "Default.html");
            // site.Invoke("Put", "SecureBindings", ":443:");
            site.Invoke("Put", "ServerAutoStart", 1);
            site.Invoke("Put", "ServerSize", 1);
            site.Invoke("SetInfo");
            // 创建应用程序虚拟目录

            DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
            siteVDir.Properties["AppIsolated"][0] = 2;
            siteVDir.Properties["Path"][0] = physicalPath;
            siteVDir.Properties["AccessFlags"][0] = 513;
            siteVDir.Properties["FrontPageWeb"][0] = 1;
            siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";
            siteVDir.Properties["AppFriendlyName"][0] = "Root";

            DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");
            //删除原应用程序池
            //foreach (DirectoryEntry a in apppools.Children)
            //{
            //    if (a.Name == webSiteName)
            //    {
            //        a.DeleteTree();
            //        a.CommitChanges();
            //    }
            //}

            DirectoryEntry newpool = apppools.Children.Add(webSiteName, "IIsApplicationPool");
            newpool.Properties["enable32BitAppOnWin64"][0] = "1"; //启动32位 IIS管理器获取该参数,应用程序池-高级设置
            newpool.Properties["AppPoolIdentityType"][0] = "4"; //4
            newpool.Properties["ManagedPipelineMode"][0] = "0"; //0:集成模式 1:经典模式
            newpool.CommitChanges();
            siteVDir.Properties["AppPoolId"][0] = webSiteName;


            siteVDir.CommitChanges();
            site.CommitChanges();
            return siteID;
        }

        /// 
        /// 得到网站的物理路径
        /// 
        /// 网站节点
        /// 
        public static string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
        {
            string physicalPath = "";
            foreach (DirectoryEntry childEntry in rootEntry.Children)
            {
                if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
                {
                    if (childEntry.Properties["Path"].Value != null)
                    {
                        physicalPath = childEntry.Properties["Path"].Value.ToString();
                    }
                    else
                    {
                        physicalPath = "";
                    }
                }
            }
            return physicalPath;
        }

        /// 
        /// 获取站点名
        /// 
        public static List GetServerBindings()
        {
            List iisList = new List();
            string entPath = String.Format("IIS://{0}/w3svc", HostName);
            DirectoryEntry ent = new DirectoryEntry(entPath);
            foreach (DirectoryEntry child in ent.Children)
            {
                if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                {
                    if (child.Properties["ServerBindings"].Value != null)
                    {
                        object objectArr = child.Properties["ServerBindings"].Value;
                        string serverBindingStr = string.Empty;
                        if (IsArray(objectArr))//如果有多个绑定站点时
                        {
                            object[] objectToArr = (object[])objectArr;
                            serverBindingStr = objectToArr[0].ToString();
                        }
                        else//只有一个绑定站点
                        {
                            serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
                        }

                        var list = "";
                        foreach (PropertyValueCollection item in child.Properties)
                        {
                            list += item.PropertyName + ":" + item.Value + "\r\n";
                        }

                        IISInfo iisInfo = new IISInfo();
                        iisInfo.DomainPort = serverBindingStr;
                        iisInfo.AppPool = child.Properties["AppPoolId"].Value.ToString();//应用程序池
                        iisList.Add(iisInfo);
                    }
                }
            }
            return iisList;
        }

        /// 
        /// 删除网站
        /// 
        /// 
        public static void DeleteWebsite(string webSiteName)
        {
            //删除旧网站
            string entPath = String.Format("IIS://{0}/w3svc", HostName);
            DirectoryEntry ent = new DirectoryEntry(entPath);

            DirectoryEntry oldWebsite = null;
            foreach (DirectoryEntry item in ent.Children)
            {
                if (item.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                {
                    var webSite = item.Properties["ServerComment"].Value.ToString();

                    if (webSite == webSiteName)
                    {
                        oldWebsite = item;
                        break;
                    }

                }   
            }

            if (oldWebsite != null)
            {
                ent.Children.Remove(oldWebsite);
                ent.CommitChanges();
            }
        }

        public static bool CreateAppPool(string appPoolName, string Username, string Password)
        {
            bool issucess = false;
            try
            {
                //创建一个新程序池
                DirectoryEntry newpool;
                DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");
                newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");

                //设置属性 访问用户名和密码 一般采取默认方式
                newpool.Properties["WAMUserName"][0] = Username;
                newpool.Properties["WAMUserPass"][0] = Password;
                newpool.Properties["AppPoolIdentityType"][0] = "3";
                newpool.CommitChanges();
                issucess = true;
                return issucess;
            }
            catch // (Exception ex)
            {
                return false;
            }
        }

        /// 
        /// 建立程序池后关联相应应用程序及虚拟目录
        /// 
        public static void SetAppToPool(string appname, string poolName)
        {
            //获取目录
            DirectoryEntry getdir = new DirectoryEntry("IIS://localhost/W3SVC");
            foreach (DirectoryEntry getentity in getdir.Children)
            {
                if (getentity.SchemaClassName.Equals("IIsWebServer"))
                {
                    //设置应用程序程序池 先获得应用程序 在设定应用程序程序池
                    //第一次测试根目录
                    foreach (DirectoryEntry getchild in getentity.Children)
                    {
                        if (getchild.SchemaClassName.Equals("IIsWebVirtualDir"))
                        {
                            //找到指定的虚拟目录.
                            foreach (DirectoryEntry getsite in getchild.Children)
                            {
                                if (getsite.Name.Equals(appname))
                                {
                                    //【测试成功通过】
                                    getsite.Properties["AppPoolId"].Value = poolName;
                                    getsite.CommitChanges();
                                }
                            }
                        }
                    }
                }
            }
        }

        /// 
        /// 判断object对象是否为数组
        /// 
        public static bool IsArray(object o)
        {
            return o is Array;
        }
    }

    public class IISInfo
    {
        public string DomainPort { get; set; }
        public string AppPool { get; set; }
    }

例子

IISWorker.CreateWebSite("TestWeb", @"D:\TestWeb", "*:12345");

参考

自写C#添加网站应用程序池虚拟目录实现网站管理 » 江湖人士

使用命令行在 Windows 11 上启用 IIS Web 服务器-云东方

用C# 代码咋管理IIS呢?_零零妖的博客-CSDN博客

C#IIS网站应用程序池列表添加修改删除 - - ITeye博客

https://www.cnblogs.com/TechSingularity/p/12017862.html

以命令方式启用或关闭Windows 10功能_参考网

你可能感兴趣的:(C#,C#,IIS)