C#操作IIS工具类(包含创建Web子程序相关方法)

因为遇到需求需要操作iis,因此做出了这个整理。

和其他人写的操作类不一样的地方主要在于,可以创建web程序的的子程序

这是一点一点循环DirectoryEntry类找到的方法,希望可以帮到各位!

如图:

 直接上工具类

  /// <summary>
    /// IIS信息获取工具
    /// </summary>
    class IISInfoTool
    {

        private static string HostName = "localhost";

        /// <summary>
        /// 通过名称获取iis站点信息
        /// </summary>
        /// <param name="name">web站点名</param>
        /// <returns></returns>
        internal static IISWebStation GetWebSite(string name)
        {
            var entry = GetWebDirectoryEntry(name);
            return entry == null ? null : new IISWebStation
                {
                    Name = entry.Properties["ServerComment"].Value.ToString(),
                    PhysicalPath = GetWebsitePhysicalPath(entry)
                };
        }

        /// <summary>
        /// 获取web站点的子应用
        /// </summary>
        /// <param name="webName">web站点名</param>
        /// <param name="subAppName">子应用名</param>
        /// <returns></returns>
        internal static IISWebStation GetWebSubSite(string webName, string subAppName)
        {
            var entry = GetSubWebDirectoryEntry(webName, subAppName);
            return entry == null ? null : new IISWebStation
            {
                Name = entry.Name,
                PhysicalPath = entry.Properties["Path"].Value.SafeToString()
            };
        }

        /// <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>
        internal static int CreateWebSite(string webSiteName, string physicalPath, string domainPort, bool isCreateAppPool)
        {
            FileTool.CreateDir(physicalPath);

            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; }
                }
            }
            // 创建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";

            if (isCreateAppPool)
            {
                CreateAppPool(webSiteName);
                siteVDir.Properties["AppPoolId"][0] = webSiteName;
            }

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

        /// <summary>
        /// 给网站创建子应用
        /// </summary>
        /// <param name="webSiteName">网站名称</param>
        /// <param name="subAppName">子应用名</param>
        /// <param name="physicalPath">物理路径</param>
        /// <param name="isCreateAppPool">是否创建应用程序池</param>
        /// <returns></returns>
        internal static int CreateWebSubSite(string webSiteName, string subAppName, string physicalPath, bool isCreateAppPool)
        {
            FileTool.CreateDir(physicalPath);

            var webEntry = GetWebDirectoryEntry(webSiteName);
            var siteID = webEntry.Name.SafeToString();

            var subRootEntry = webEntry.Children.Find("ROOT", "IIsWebVirtualDir");

            DirectoryEntry siteVDir = subRootEntry.Children.Add(subAppName, "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/" + subAppName;
            siteVDir.Properties["AppFriendlyName"][0] = subAppName;

            if (isCreateAppPool)
            {
                CreateAppPool(subAppName);
                siteVDir.Properties["AppPoolId"][0] = subAppName;
            }
            siteVDir.CommitChanges();
            return 1;
        }

        /// <summary>
        /// 创建应用程序池
        /// </summary>
        /// <param name="appPoolName">应用程序池名</param>
        private static void CreateAppPool(string appPoolName)
        {
            DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");

            DirectoryEntry newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
            newpool.Properties["AppPoolIdentityType"][0] = "4"; //4
            newpool.Properties["ManagedPipelineMode"][0] = "0"; //0:集成模式 1:经典模式
            //newpool.Properties["ManagedRuntimeVersion"][0] = "";  //.net clr版本 空字符串就是“无托管代码”
            newpool.CommitChanges();
        }

        /// <summary>
        /// 获取web站点的子应用,返回虚拟路径对象
        /// </summary>
        /// <param name="webName">web站点名</param>
        /// <param name="subAppName">子应用名</param>
        /// <returns></returns>
        private static DirectoryEntry GetSubWebDirectoryEntry(string webName, string subAppName)
        {
            var webEntry = GetWebDirectoryEntry(webName);
            if (webEntry == null) return null;

            var subRootEntry = webEntry.Children.Find("ROOT", "IIsWebVirtualDir");
            if (subRootEntry == null) return null;

            try
            {
                return subRootEntry.Children.Find(subAppName, "IIsWebVirtualDir");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLine(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 通过名称获取iis站点信息,返回虚拟路径对象
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static DirectoryEntry GetWebDirectoryEntry(string name)
        {
            return GetAllWebDirectoryEntry().FirstOrDefault(a => a.Properties["ServerComment"].Value.ToString() == name);
        }

        /// <summary>
        /// 获取所有的iis站点信息,返回虚拟路径对象
        /// </summary>
        /// <returns></returns>
        private static IEnumerable<DirectoryEntry> GetAllWebDirectoryEntry()
        {
            DirectoryEntry rootEntry = new DirectoryEntry("IIS://" + HostName + "/W3SVC");

            var stations = new List<DirectoryEntry>();
            foreach (DirectoryEntry entry in rootEntry.Children)
            {
                if (!entry.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase)) continue;
                stations.Add(entry);
            }
            return stations;
        }

        /// <summary>
        /// 通过DirectoryEntry对象获取对应的物理路径
        /// </summary>
        /// <param name="rootEntry"></param>
        /// <returns></returns>
        private 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;
        }
    }
原文地址:https://www.cnblogs.com/gamov/p/12658343.html