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

这篇具有很好参考价值的文章主要介绍了【C#】通过C#代码创建IIS应用程序池和网站。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

代码

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

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

        /// <summary>
        /// 获取本地IIS版本
        /// </summary>
        /// <returns></returns>
        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;
            }
        }

        /// <summary>
        /// 创建虚拟目录网站
        /// </summary>
        /// <param name="webSiteName">网站名称</param>
        /// <param name="physicalPath">物理路径</param>
        /// <param name="domainPort">站点+端口,如192.168.1.23:90</param>
        /// <param name="isCreateAppPool">是否创建新的应用程序池</param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 得到网站的物理路径
        /// </summary>
        /// <param name="rootEntry">网站节点</param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 获取站点名
        /// </summary>
        public static List<IISInfo> GetServerBindings()
        {
            List<IISInfo> iisList = new List<IISInfo>();
            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;
        }

        /// <summary>
        /// 删除网站
        /// </summary>
        /// <param name="webSiteName"></param>
        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;
            }
        }

        /// <summary>
        /// 建立程序池后关联相应应用程序及虚拟目录
        /// </summary>
        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();
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 判断object对象是否为数组
        /// </summary>
        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功能_参考网文章来源地址https://www.toymoban.com/news/detail-643827.html

到了这里,关于【C#】通过C#代码创建IIS应用程序池和网站的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ASP.NET Core应用程序在IIS服务器上的运行环境介绍和下载安装(超详细)

    要想在 IIS 上成功运行 ASP.NET Core 应用程序,我们需要有ASP.NET Core 运行时和ASP.NET Core Module。而在这里我们仅需要下载ASP.NET Core Hosting Bundle 即可,这是为什么呢? 想了解的可以看文章末节的介绍。 ASP.NET 核心运行时使你能够运行现有的 Web/服务器应用程序。 在 Windows 上,我们

    2024年02月11日
    浏览(43)
  • 基于C#的画图应用程序(窗体应用程序)C#组件、控件

      使用VS2019,建立窗体应用程序,借助一系列控件实现画图功能。   结合组件与控件的使用。 目录 一、预备知识 1、什么是C#的组件和控件 (1)共同点 (2)不同点 二、主要步骤 1、软件以及环境 2、设置接口 3、界面设计 4、编写代码 5、编译程序和运行 三、编写代码 1、设

    2023年04月08日
    浏览(45)
  • 《深入浅出.NET框架设计与实现》笔记6.2——ASP.NET Core应用程序多种运行模式之二——IIS 服务承载

     ASP.NET Core应用程序可以在多种运行模式下运行,包括自宿主(Self-Hosting)、IIS服务承载、桌面应用程序、服务承载。 因此选择和时的模式很重要。 IIS 服务承载 将 ASP.NET Core 应用程序托管在 Internet Information Services (IIS) 中。 利用 IIS 提供的高级功能,如负载均衡、HTTPS 支持和

    2024年04月26日
    浏览(42)
  • C# 记事本应用程序

    2024年02月10日
    浏览(39)
  • C# 应用程序强制获取焦点

    Windorm和WPF等应用程序想自己获取焦点焦点那是不可能的,只能通过系统的API来实现 上面第一个函数获取的是当前窗体的句柄,  如果窗体应用要获取自己的句柄的话就使用下面的方法获取 拿到句柄的话我们就可以使用SetForegroundWindow将窗体设置为前台应用 这可以能还不够,

    2024年02月12日
    浏览(30)
  • C#桌面程序 winform 集成内置WebApi C# 创建HTTP Web API服务,winform项目创建HTTP WEB服务,不使用IIS业务 C#桌面程序WebApi C#winform集

     在维护旧的项目时,有时需要提供APP连接的需求,就要提供HTTP服务,winform项目就要提供HTTP服务,就不用再去写个c# web的IIS相关的业务了,简化项目的复杂度。只需要简单化实例就可以实现提供HTTP服务

    2024年02月08日
    浏览(44)
  • C#程序设计之windows应用程序设计基础

    题目描述 设计一个“简单通讯录”程序,在窗体上建立一个下拉式列表框、两个文本框和两个标签,实现以下功能:当用户在下拉式列表框中选择一个学生姓名后,在“学生姓名”、“地址”两个文本框中分别显示出对应的学生和地址。 代码 窗体代码 运行结果 题目描述 设

    2024年02月06日
    浏览(41)
  • C#桌面应用程序开发的学习路线

    C#桌面应用程序开发的学习路线。以下是一个基本的学习路线,供你参考: 1. C#基础 学习C#的基本语法和面向对象编程(OOP)的概念 了解C#的数据类型、变量和常量 学习控制结构(如条件语句、循环语句)和函数 2. .NET框架和Windows Forms 了解.NET框架的基本概念和架构 学习使用

    2024年02月10日
    浏览(32)
  • Windows 通过端口占用查找应用程序

    对于开发人员在启动项目的过程中也许会遇到程序使用 端口被占用的情况;如下: 遇到这种情况我们可以换一个端口,也可以查找是哪个程序暂用了这个端口;在Windows上我们可以通过如下方式去查找对应的端口程序信息。 1、打开dos命令窗口 开始—-运行—-cmd,或者是wind

    2024年02月12日
    浏览(34)
  • 怎么创建JDBC应用程序

    建立一个JDBC应用程序,本教程中以Java连接MySQL为一个示例,分六个步骤进行: 1. 导入包 在程序中包含数据库编程所需的JDBC类。大多数情况下,使用 import java.sql.* 就足够了,如下所示: 2. 注册JDBC驱动程序 需要初始化驱动程序,这样就可以打开与数据库的通信。以下是代码

    2024年02月15日
    浏览(59)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包