DirectoryEntry IIS操作

25 篇文章 0 订阅

http://blog.csdn.net/qq254331474/article/details/53302622


代码都是通过网上资料查找,有些方法是直接Copy网友的(感谢网友们的资料分享微笑),自己总合到一个类中.这个类对于IIS的增/删/改/查都可以.把代码共享出来,希望对这方面的人有帮助....

建议使用"Microsoft.Web.Administration.dll"..


[csharp]  view plain  copy
  1. /// <summary>  
  2.    /// 管理IIS网站  
  3.    /// </summary>  
  4.    public class IISManager  
  5.    {  
  6.        private readonly String _hostName = "localhost";  
  7.   
  8.        private readonly DirectoryEntry rootEntry = null;  
  9.   
  10.        public IISManager(String hostName = "")  
  11.        {  
  12.            _hostName = hostName;  
  13.            rootEntry = new DirectoryEntry("IIS://" + _hostName + "/W3SVC");  
  14.        }  
  15.        public IISManager(String hostName = "", String Username = "", String Password = "")  
  16.            : this(hostName)  
  17.        {  
  18.            _hostName = hostName;  
  19.        }  
  20.   
  21.        /// <summary>  
  22.        /// 获取本地IIS版本  
  23.        /// </summary>  
  24.        /// <returns></returns>  
  25.        public String GetIISVersion()  
  26.        {  
  27.            try  
  28.            {  
  29.                DirectoryEntry entry = new DirectoryEntry("IIS://" + _hostName + "/W3SVC/INFO");  
  30.                return entry.Properties["MajorIISVersionNumber"].Value.ToString();  
  31.            }  
  32.            catch (Exception se)  
  33.            {  
  34.                //说明一点:IIS5.0中没有(int)entry.Properties["MajorIISVersionNumber"].Value;属性,  
  35.                //将抛出异常 证明版本为 5.0  
  36.                return String.Empty;  
  37.            }  
  38.        }  
  39.   
  40.        /// <summary>  
  41.        /// 创建虚拟目录网站  
  42.        /// </summary>  
  43.        /// <param name="webSiteName">网站名称</param>  
  44.        /// <param name="physicalPath">物理路径</param>  
  45.        /// <param name="domainPort">站点+端口,如192.168.1.23:90</param>  
  46.        /// <param name="serverState">WEB启动状态</param>  
  47.        /// <returns></returns>  
  48.        public void CreateWebSite(String webSiteName, String physicalPath, String domainPort, String serverState)  
  49.        {  
  50.            // 为新WEB站点查找一个未使用的ID  
  51.            int siteID = 1;  
  52.            foreach (DirectoryEntry e in rootEntry.Children)  
  53.            {  
  54.                if (e.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))  
  55.                {  
  56.                    int ID = Convert.ToInt32(e.Name);  
  57.                    if (ID >= siteID) { siteID = ID + 1; }  
  58.                }  
  59.            }  
  60.            //是否应该创建目录  
  61.            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(physicalPath);  
  62.            if (!dir.Exists) { dir.Create(); }  
  63.   
  64.            // 创建WEB站点  
  65.            DirectoryEntry site = (DirectoryEntry)rootEntry.Invoke(State.Create.ToString(), new Object[] { "IIsWebServer", siteID });  
  66.            site.Invoke("Put""ServerComment", webSiteName);  
  67.            site.Invoke("Put""KeyType""IIsWebServer");  
  68.            site.Invoke("Put""ServerBindings", domainPort + ":");  
  69.            site.Invoke("Put""ServerState", serverState);  
  70.            //site.Invoke("Put", "FrontPageWeb", 1);  
  71.            //site.Invoke("Put", "DefaultDoc", "Login.html");  
  72.            // site.Invoke("Put", "SecureBindings", ":443:");  
  73.            //site.Invoke("Put", "ServerAutoStart", 1);  
  74.            //site.Invoke("Put", "ServerSize", 1);  
  75.            site.Invoke("SetInfo");  
  76.            // 创建应用程序虚拟目录  
  77.            DirectoryEntry siteVDir = site.Children.Add("Root""IISWebVirtualDir");  
  78.            siteVDir.Properties["Path"][0] = physicalPath;  
  79.   
  80.            //siteVDir.Properties["AppIsolated"][0] = 2;  
  81.            //siteVDir.Properties["AccessFlags"][0] = 513;  
  82.            //siteVDir.Properties["FrontPageWeb"][0] = 1;  
  83.            //siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";  
  84.            //siteVDir.Properties["AppFriendlyName"][0] = "Root";  
  85.            siteVDir.CommitChanges();  
  86.            site.CommitChanges();  
  87.        }  
  88.   
  89.        public void UpdateIISWebSite(String oldWebSiteName, String webSiteName, String physicalPath,  
  90.            String domainPort, String serverState)  
  91.        {  
  92.            DirectoryEntry childrenEntry = this.DirectoryEntryChildren(oldWebSiteName);  
  93.            childrenEntry.Properties["ServerComment"].Value = webSiteName;  
  94.            childrenEntry.Properties["ServerState"].Value = serverState;  
  95.            childrenEntry.Properties["ServerBindings"].Value = domainPort + ":";  
  96.            //更新程序所在目录  
  97.            foreach (DirectoryEntry childrenDir in childrenEntry.Children)  
  98.            {  
  99.                if (childrenDir.SchemaClassName.Equals("IISWebVirtualDir", StringComparison.OrdinalIgnoreCase))  
  100.                {  
  101.                    childrenDir.Properties["Path"].Value = physicalPath;  
  102.                    childrenDir.CommitChanges();  
  103.                    childrenEntry.CommitChanges();  
  104.                    return;  
  105.                }  
  106.            }  
  107.        }  
  108.  
  109.        #region IISWeb 启动/停止/删除  
  110.        public void StartWebSite(String serverComment)  
  111.        {  
  112.            DirectoryEntry children = this.DirectoryEntryChildren(serverComment);  
  113.            if (children != null)  
  114.            {  
  115.                children.Invoke(State.Start.ToString(), new Object[] { });  
  116.            }  
  117.        }  
  118.        public void StartWebSite(Int32 name)  
  119.        {  
  120.            this.WebEnable(name, State.Start);  
  121.        }  
  122.        public void ResetWebSite(String serverComment)  
  123.        {  
  124.            DirectoryEntry children = this.DirectoryEntryChildren(serverComment);  
  125.            if (children != null)  
  126.            {  
  127.                children.Invoke(State.Reset.ToString(), new Object[] { });  
  128.            }  
  129.        }  
  130.        public void ResetWebSite(Int32 name)  
  131.        {  
  132.            this.WebEnable(name, State.Reset);  
  133.        }  
  134.        public void StopWebSite(String serverComment)  
  135.        {  
  136.            DirectoryEntry children = this.DirectoryEntryChildren(serverComment);  
  137.            if (children != null)  
  138.            {  
  139.                children.Invoke(State.Stop.ToString(), new Object[] { });  
  140.            }  
  141.        }  
  142.        public void StopWebSite(Int32 name)  
  143.        {  
  144.            this.WebEnable(name, State.Stop);  
  145.        }  
  146.        /// <summary>  
  147.        /// 依据网站名称删除  
  148.        /// <param name="serverComment">网站名称:如:Test</param>  
  149.        /// </summary>  
  150.        public void RemoveIISWebServer(String serverComment)  
  151.        {  
  152.            DirectoryEntry children = this.DirectoryEntryChildren(serverComment);  
  153.            if (children != null)  
  154.            {  
  155.                //this.st(serverComment); //先停止IIS程序池  
  156.                children.DeleteTree();  
  157.            }  
  158.        }  
  159.        /// <summary>  
  160.        /// 依据网站名称在IIS中的排列顺序删除  
  161.        /// <param name="name">排列顺序:如:Test的</param>  
  162.        /// </summary>  
  163.        public void RemoveIISWebServer(Int32 name)  
  164.        {  
  165.            DirectoryEntry siteEntry = new DirectoryEntry("IIS://" + _hostName + "/W3SVC/" + name);  
  166.            siteEntry.DeleteTree();  
  167.        }  
  168.   
  169.        private void WebEnable(Int32 name, State state)  
  170.        {  
  171.            DirectoryEntry siteEntry = new DirectoryEntry("IIS://" + _hostName + "/W3SVC/" + name);  
  172.            siteEntry.Invoke(state.ToString(), new Object[] { });  
  173.        }  
  174.        private DirectoryEntry DirectoryEntryChildren(String serverComment)  
  175.        {  
  176.            foreach (DirectoryEntry entry in rootEntry.Children)  
  177.            {  
  178.                if (entry.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))  
  179.                {  
  180.                    if (entry.Properties["ServerComment"].Value.ToString()  
  181.                        .Equals(serverComment, StringComparison.OrdinalIgnoreCase))  
  182.                    {  
  183.                        return entry;  
  184.                    }  
  185.                }  
  186.            }  
  187.            return null;  
  188.        }  
  189.        #endregion  
  190.  
  191.        #region 注释得到物理路径+程序池  
  192.        / <summary>  
  193.        / 得到网站的物理路径  
  194.        / </summary>  
  195.        / <param name="rootEntry">网站节点</param>  
  196.        / <returns></returns>  
  197.        //private String GetWebsitePhysicalPath(DirectoryEntry rootEntry)  
  198.        //{  
  199.        //    return GetDirectoryEntryChildren(rootEntry, "Path");  
  200.        //}  
  201.        / <summary>  
  202.        / 得到网站的物理路径  
  203.        / </summary>  
  204.        / <param name="rootEntry">网站节点</param>  
  205.        / <returns></returns>  
  206.        //private String GetAppPoop(DirectoryEntry rootEntry)  
  207.        //{  
  208.        //    return GetDirectoryEntryChildren(rootEntry, "AppPoolId");  
  209.        //}  
  210.        //private String GetDirectoryEntryChildren(DirectoryEntry rootEntry, String properties)  
  211.        //{  
  212.        //    String propValue = String.Empty;  
  213.        //    foreach (DirectoryEntry childEntry in rootEntry.Children)  
  214.        //    {  
  215.        //        if ((childEntry.SchemaClassName.Equals("IIsWebVirtualDir", StringComparison.OrdinalIgnoreCase))  
  216.        //            && (childEntry.Name.Equals("root", StringComparison.OrdinalIgnoreCase)))  
  217.        //        {  
  218.        //            if (childEntry.Properties[properties].Value != null)  
  219.        //            {  
  220.        //                propValue = childEntry.Properties[properties].Value.ToString();  
  221.        //            }  
  222.        //        }  
  223.        //    }  
  224.        //    return propValue;  
  225.        //}   
  226.        #endregion  
  227.   
  228.        public bool AnyServerComment(String serverComment)  
  229.        {  
  230.            List<IISWebManager> list = this.ServerBindings();  
  231.            Boolean flag = list.Any<IISWebManager>(w => w.ServerComment.Equals(serverComment, StringComparison.OrdinalIgnoreCase));  
  232.            return flag;  
  233.        }  
  234.        public bool AnyDomainProt(Int32 domainPort)  
  235.        {  
  236.            List<IISWebManager> list = this.ServerBindings();  
  237.            Boolean flag = list.Any<IISWebManager>(w => w.DomainPort == domainPort);  
  238.            return flag;  
  239.        }  
  240.        /// <summary>  
  241.        /// 获取站点信息  
  242.        /// </summary>  
  243.        public List<IISWebManager> ServerBindings()  
  244.        {  
  245.            List<IISWebManager> iislist = new List<IISWebManager>();  
  246.            DirectoryEntry rootChildrenEntry = null;  
  247.            IEnumerator enumeratorRoot = null;  
  248.            foreach (DirectoryEntry entry in rootEntry.Children)  
  249.            {  
  250.                if (entry.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))  
  251.                {  
  252.                    var props = entry.Properties;  
  253.   
  254.                    // if (props["ServerComment"][0].ToString().Contains("Default")) { continue; }  
  255.                    //获取网站绑定的IP,端口,主机头  
  256.                    String[] serverBindings = props["ServerBindings"].Value.ToString().Split(':');  
  257.                    var physicalPath = "";  
  258.                    var appPoolId = "";  
  259.                    enumeratorRoot = entry.Children.GetEnumerator();  
  260.                    while (enumeratorRoot.MoveNext())  
  261.                    {  
  262.                        rootChildrenEntry = (DirectoryEntry)enumeratorRoot.Current;  
  263.                        appPoolId = rootChildrenEntry.Properties["AppPoolId"].Value.ToString();  
  264.                        if (rootChildrenEntry.SchemaClassName.Equals("IIsWebVirtualDir", StringComparison.OrdinalIgnoreCase))  
  265.                        {  
  266.                            physicalPath = rootChildrenEntry.Properties["Path"].Value.ToString();  
  267.                            break;  
  268.                        }  
  269.                    }  
  270.   
  271.                    iislist.Add(new IISWebManager()  
  272.                    {  
  273.                        Name = Convert.ToInt32(entry.Name),  
  274.                        ServerComment = props["ServerComment"].Value.ToString(),  
  275.                        DomainIP = serverBindings[0].ToString(),  
  276.                        DomainPort = Convert.ToInt32(serverBindings[1]),  
  277.                        ServerState = props["ServerState"][0].ToString(),//运行状态  
  278.                        PhysicalPath = physicalPath,  
  279.                        AppPoolId = appPoolId  
  280.                    });  
  281.   
  282.                    //String EnableDeDoc = props["EnableDefaultDoc"][0].ToString();  
  283.                    //String DefaultDoc = props["DefaultDoc"][0].ToString();//默认文档  
  284.                    //String MaxConnections = props["MaxConnections"][0].ToString();//iis连接数,-1为不限制  
  285.                    //String ConnectionTimeout = props["ConnectionTimeout"][0].ToString();//连接超时时间  
  286.                    //String MaxBandwidth = props["MaxBandwidth"][0].ToString();//最大绑定数  
  287.                    //String ServerState = props["ServerState"][0].ToString();//运行状态  
  288.                    //var ServerComment = (String)Server.Properties["ServerComment"][0];  
  289.                    //var AccessRead = (Boolean)Server.Properties["AccessRead"][0];  
  290.                    //var AccessScript = (Boolean)Server.Properties["AccessScript"][0];  
  291.                    //var DefaultDoc = (String)Server.Properties["DefaultDoc"][0];  
  292.                    //var EnableDefaultDoc = (Boolean)Server.Properties["EnableDefaultDoc"][0];  
  293.                    //var EnableDirBrowsing = (Boolean)Server.Properties["EnableDirBrowsing"][0];  
  294.                    //var Port = Convert.ToInt32(((String)Server.Properties["Serverbindings"][0])  
  295.                    //   .Substring(1, ((String)Server.Properties["Serverbindings"][0]).Length - 2));  
  296.   
  297.                    //ieRoot = Root.Children.GetEnumerator();  
  298.                    //while (ieRoot.MoveNext())  
  299.                    //{  
  300.                    //    VirDir = (DirectoryEntry)ieRoot.Current;  
  301.                    //    if (VirDir.SchemaClassName != "IIsWebVirtualDir" && VirDir.SchemaClassName != "IIsWebDirectory")  
  302.                    //        continue;  
  303.                    //    var TName = VirDir.Name;  
  304.                    //    var TAccessRead = (Boolean)VirDir.Properties["AccessRead"][0];  
  305.                    //    var TAccessScript = (Boolean)VirDir.Properties["AccessScript"][0];  
  306.                    //    var TDefaultDoc = (String)VirDir.Properties["DefaultDoc"][0];  
  307.                    //    var TEnableDefaultDoc = (Boolean)VirDir.Properties["EnableDefaultDoc"][0];  
  308.                    //    if (VirDir.SchemaClassName == "IIsWebVirtualDir")  
  309.                    //    {  
  310.                    //        var TPath = (String)VirDir.Properties["Path"][0];  
  311.                    //    }  
  312.                    //    else if (VirDir.SchemaClassName == "IIsWebDirectory")  
  313.                    //    {  
  314.                    //        var TPath = Root.Properties["Path"][0] + @"\" + VirDir.Name;  
  315.                    //    }  
  316.                    //}  
  317.                    取全部的字段  
  318.                    //String str = "";  
  319.                    //System.DirectoryServices.PropertyCollection props = entry.Properties;  
  320.                    //foreach (String name in props.PropertyNames)  
  321.                    //{  
  322.                    //    foreach (Object o in props[name])  
  323.                    //    {  
  324.                    //        str += name.ToString() + ":" + o.ToString() + "\n";  
  325.                    //    }  
  326.                    //}  
  327.                }  
  328.            }  
  329.            return iislist;  
  330.        }  
  331.   
  332.   
  333.   
  334.        public List<IISAppPoolInfo> GetAppPools()  
  335.        {  
  336.            List<IISAppPoolInfo> list = new List<IISAppPoolInfo>();  
  337.            DirectoryEntry appPoolEntry = new DirectoryEntry(String.Format("IIS://{0}/W3SVC/AppPools", _hostName));  
  338.            foreach (DirectoryEntry entry in appPoolEntry.Children)  
  339.            {  
  340.                var schmeName = entry.Name;  
  341.                list.Add(new IISAppPoolInfo()  
  342.                {  
  343.                    AppPoolName = entry.Name,  
  344.                    AppPoolIdentityType = entry.Properties["AppPoolIdentityType"].Value.ToString(),  
  345.                    AppPoolCommand = Convert.ToInt32(entry.Properties["AppPoolCommand"].Value),  
  346.                    AppPoolState = Convert.ToInt32(entry.Properties["AppPoolState"].Value),  
  347.                    ManagedPipelineMode = Convert.ToInt32(entry.Properties["ManagedPipelineMode"].Value),  
  348.                    ManagedRuntimeVersion = entry.Properties["ManagedRuntimeVersion"].Value.ToString()  
  349.                });  
  350.            }  
  351.            return list;  
  352.        }  
  353.        public Boolean DeleteAppPool(String appPool)  
  354.        {  
  355.            Boolean flag = false;  
  356.            if (String.IsNullOrEmpty(appPool)) return flag;  
  357.            DirectoryEntry de = new DirectoryEntry(String.Format("IIS://{0}/W3SVC/AppPools", _hostName));  
  358.            foreach (DirectoryEntry entry in de.Children)  
  359.            {  
  360.                if (entry.Name.Equals(appPool, StringComparison.OrdinalIgnoreCase))  
  361.                {  
  362.                    try  
  363.                    {  
  364.                        entry.DeleteTree();  
  365.                        flag = true;  
  366.                    }  
  367.                    catch  
  368.                    {  
  369.                        flag = false;  
  370.                    }  
  371.                }  
  372.            }  
  373.            return flag;  
  374.        }  
  375.        /// <summary>  
  376.        /// 判断程序池是否存在  
  377.        /// </summary>  
  378.        /// <param name="AppPoolName">程序池名称</param>  
  379.        /// <returns>true存在 false不存在</returns>  
  380.        public Boolean IsAppPoolName(String AppPoolName)  
  381.        {  
  382.            Boolean result = false;  
  383.            DirectoryEntry appPools = new DirectoryEntry(String.Format("IIS://{0}/W3SVC/AppPools", _hostName));  
  384.            foreach (DirectoryEntry getdir in appPools.Children)  
  385.            {  
  386.                if (getdir.Name.Equals(AppPoolName))  
  387.                {  
  388.                    result = true;  
  389.                    return result;  
  390.                }  
  391.            }  
  392.            return result;  
  393.        }  
  394.   
  395.        public Boolean CreateAppPool(String appPoolName, String appPoolCommand, String appPoolState,  
  396.            String managedPipelineMode, String managedRuntimeVersion,  
  397.            String appPoolIdentityType, String Username, String Password)  
  398.        {  
  399.            Boolean issucess = false;  
  400.            try  
  401.            {  
  402.                //创建一个新程序池  
  403.                DirectoryEntry apppools = new DirectoryEntry("IIS://" + _hostName + "/W3SVC/AppPools");  
  404.                DirectoryEntry newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");  
  405.   
  406.                //设置属性 访问用户名和密码 一般采取默认方式  
  407.                newpool.Properties["WAMUserName"][0] = Username;  
  408.                newpool.Properties["WAMUserPass"][0] = Password;  
  409.   
  410.                //newpool.Properties["AppPoolIdentityType"].Value = "4"; //这个默认,不晓得是什么参数  
  411.                newpool.Properties["AppPoolCommand"].Value = appPoolCommand;  
  412.                newpool.Properties["AppPoolState"].Value = appPoolState;  
  413.                newpool.Properties["ManagedPipelineMode"].Value = managedPipelineMode;  
  414.                newpool.Properties["ManagedRuntimeVersion"].Value = managedRuntimeVersion;  
  415.   
  416.                newpool.CommitChanges();  
  417.                issucess = true;  
  418.                return issucess;  
  419.            }  
  420.            catch // (Exception ex)   
  421.            {  
  422.                return false;  
  423.            }  
  424.        }  
  425.   
  426.        public Boolean UpdateAppPool(String appPoolName, String appPoolCommand,  
  427.            String appPoolState, String managedPipelineMode, String managedRuntimeVersion,  
  428.            String Username, String Password)  
  429.        {  
  430.            Boolean issucess = false;  
  431.            try  
  432.            {  
  433.                DirectoryEntry appPoolEntry = new DirectoryEntry(String.Format("IIS://{0}/W3SVC/AppPools", _hostName));  
  434.                foreach (DirectoryEntry entry in appPoolEntry.Children)  
  435.                {  
  436.                    if (entry.Name.Equals(appPoolName, StringComparison.OrdinalIgnoreCase))  
  437.                    {  
  438.                        // entry.Properties["AppPoolIdentityType"].Value = appPoolIdentityType;  
  439.                        entry.Properties["AppPoolCommand"].Value = appPoolCommand;  
  440.                        entry.Properties["AppPoolState"].Value = appPoolState;  
  441.                        entry.Properties["ManagedPipelineMode"].Value = managedPipelineMode;  
  442.                        entry.Properties["ManagedRuntimeVersion"].Value = managedRuntimeVersion;  
  443.                        entry.CommitChanges();  
  444.                        issucess = true;  
  445.                        return issucess;  
  446.                    }  
  447.                }  
  448.            }  
  449.            catch // (Exception ex)   
  450.            {  
  451.            }  
  452.            return issucess;  
  453.        }  
  454.   
  455.   
  456.        /// <summary>  
  457.        /// 建立程序池后关联相应应用程序  
  458.        /// </summary>  
  459.        public void SetAppToPool(String appname, String poolName)  
  460.        {  
  461.            DirectoryEntry children = this.DirectoryEntryChildren(appname);  
  462.            foreach (DirectoryEntry childrenRoot in children.Children)  
  463.            {  
  464.                if (childrenRoot.SchemaClassName.Equals("IIsWebVirtualDir", StringComparison.OrdinalIgnoreCase))  
  465.                {  
  466.                    childrenRoot.Properties["AppPoolId"].Value = poolName;  
  467.                    childrenRoot.CommitChanges();  
  468.                    return;  
  469.                }  
  470.            }  
  471.        }  
  472.    }  
  473.   
  474.    /// <summary>  
  475.    /// IIS应用程序池  
  476.    /// </summary>  
  477.    public class IISAppPoolInfo  
  478.    {  
  479.        /// <summary>  
  480.        /// 应用程序池名称  
  481.        /// </summary>  
  482.        public String AppPoolName { setget; }  
  483.   
  484.        public String AppPoolIdentityType { getset; }  
  485.   
  486.        private Int32 _AppPoolState = 2;  
  487.        /// <summary>  
  488.        /// 是否启动:2:启动,4:停止,XX:回收  
  489.        /// </summary>  
  490.        public Int32 AppPoolState  
  491.        {  
  492.            get { return _AppPoolState; }  
  493.            set { _AppPoolState = value; }  
  494.        }  
  495.        private Int32 _AppPoolCommand = 1;  
  496.        /// <summary>  
  497.        /// 立即启动应用程序池.1:以勾选,2:未勾选  
  498.        /// </summary>  
  499.        public Int32 AppPoolCommand  
  500.        {  
  501.            get { return _AppPoolCommand; }  
  502.            set { _AppPoolCommand = value; }  
  503.        }  
  504.        /// <summary>  
  505.        /// .NET Framework版本.  
  506.        /// "":无托管代码,V2.0: .NET Framework V2.0XXXX,V4.0: .NET Framework V4.0XXXX  
  507.        /// </summary>  
  508.        public String ManagedRuntimeVersion { getset; }  
  509.   
  510.        private Int32 _ManagedPipelineMode = 0;  
  511.        /// <summary>  
  512.        /// 托管管道模式.0:集成,1:经典  
  513.        /// </summary>  
  514.        public Int32 ManagedPipelineMode  
  515.        {  
  516.            get { return _ManagedPipelineMode; }  
  517.            set { _ManagedPipelineMode = value; }  
  518.        }  
  519.    }  
  520.    public sealed class IISWebManager  
  521.    {  
  522.        /// <summary>  
  523.        /// 网站名称ID  
  524.        /// </summary>  
  525.        public Int32 Name { getset; }  
  526.        /// <summary>  
  527.        /// 网名名称  
  528.        /// </summary>  
  529.        public String ServerComment { getset; }  
  530.        /// <summary>  
  531.        /// 应用程序池  
  532.        /// </summary>  
  533.        public String AppPoolId { setget; }  
  534.        /// <summary>  
  535.        /// 物理路径  
  536.        /// </summary>  
  537.        public String PhysicalPath { setget; }  
  538.        /// <summary>  
  539.        /// 绑定类型  
  540.        /// </summary>  
  541.        public String DomainType { setget; }  
  542.        /// <summary>  
  543.        /// 绑定IP  
  544.        /// </summary>  
  545.        public String DomainIP { setget; }  
  546.   
  547.        /// <summary>  
  548.        /// 绑定端口  
  549.        /// </summary>  
  550.        public Int32 DomainPort { setget; }  
  551.        /// <summary>  
  552.        /// 是否启动:2:启动,4:停止  
  553.        /// </summary>  
  554.        public String ServerState { setget; }  
  555.        /// <summary>  
  556.        /// 服务命令  
  557.        /// </summary>  
  558.        public String ServerCommand { getset; }  
  559.   
  560.    }  




using Microsoft.Web.Administration;  //C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApplication14
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //ServerManager sm = new ServerManager();
            //Site site = sm.Sites["yp20180301"];
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.43.94"),9875);
            //site.Bindings[0].EndPoint.Port = 9875;


            sm.Sites.Remove(site);


            //sm.CommitChanges();


            //
            System.DirectoryServices.DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC");
            foreach (System.DirectoryServices.DirectoryEntry item in folderRoot.Children)
            {
                if (item.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                {
                    if(item.Properties["ServerComment"].Value.ToString()== "yp20180301")
                    {


                    }
                }
            }
            //得到现默认站点的IP 端口 描述        
            string strServerBindings  = folderRoot.Properties["ServerBindings"].Value.ToString();
            //解出端口Port
            char[] splitChar = { ':' };
            string[] strArr = strServerBindings.Split(splitChar);
            //重新赋值为8000
            folderRoot.Properties["ServerBindings"].Value = strArr[0] + ":9875:" + strArr[2];
            folderRoot.CommitChanges();
            string Text = folderRoot.Properties["ServerBindings"].Value.ToString();


        }
    }

}



###################################################################

using Microsoft.Web.Administration;  //C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApplication14
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            
        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {


                //
                string _strHostIp = siteName.Text;
                bool _bSuccess = false;
                System.DirectoryServices.DirectoryEntry folderRoot = new DirectoryEntry("IIS://" + _strHostIp + "/W3SVC");
                foreach (System.DirectoryServices.DirectoryEntry item in folderRoot.Children)
                {
                    if (item.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                    {
                        if (item.Properties["ServerComment"].Value.ToString() == comboBoxSiteName.Text)
                        {
                            //得到站点的IP 端口 描述
                            string strServerBindings = item.Properties["ServerBindings"].Value.ToString();
                            //解出端口Port
                            char[] splitChar = { ':' };
                            string[] strArr = strServerBindings.Split(splitChar);


                            item.Properties["ServerBindings"].Value = strArr[0] + ":" + int.Parse(port.Text) + ":" + strArr[2];
                            


                            
                            item.CommitChanges();
                            _bSuccess = true;
                            break;
                            
                        }
                    }
                }
                if(_bSuccess)
                {
                    MessageBox.Show("设置成功!");
                }
                else
                {
                    MessageBox.Show("设置失败!请确认网站名称是否有误。");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            
        }


        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string _strHostIp = siteName.Text;


                string _strAssemblyFullName = "";
                List<string> _listStrAssemblyFullNmae = new List<string>();
                System.DirectoryServices.DirectoryEntry folderRoot = new DirectoryEntry("IIS://" + _strHostIp + "/W3SVC");
                foreach (System.DirectoryServices.DirectoryEntry item in folderRoot.Children)
                {
                    if (item.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                    {
                        if (item.Properties["ServerComment"].Value.ToString() == comboBoxSiteName.Text)
                        {


                            string _strDirectoryFullName = "";
                            foreach (DirectoryEntry item2 in item.Children)
                            {
                                if (item2.SchemaClassName.Equals("IISWebVirtualDir", StringComparison.OrdinalIgnoreCase))
                                {
                                    string _str11 = item2.Properties["Path"].Value.ToString();
                                    _strDirectoryFullName += _str11 + "\\bin";
                                    break;
                                }
                            }
                            if (!string.IsNullOrEmpty(_strDirectoryFullName))
                            {
                                DirectoryInfo _directoryInfo = new DirectoryInfo(_strDirectoryFullName);
                                FileInfo[] _files = _directoryInfo.GetFiles();
                                foreach (FileInfo file in _files)
                                {
                                    if (file.Extension == ".dll")
                                    {
                                        if (file.Name.IndexOf("Microsoft") > -1)
                                            continue;
                                        _strAssemblyFullName = file.FullName;
                                    }
                                }
                                _listStrAssemblyFullNmae.Add(_strAssemblyFullName);
                            }




                            break;


                        }
                    }
                }


                //
                
                if(_listStrAssemblyFullNmae.Count!=0)
                {
                    foreach (string assemblyName in _listStrAssemblyFullNmae)
                    {
                        try
                        {
                            Assembly _assembly = Assembly.LoadFrom(_strAssemblyFullName);//@"E:\webServiceTest1\bin\WebApplication4.dll"
                            Type[] _types = _assembly.GetTypes();
                            foreach (var _type in _types)
                            {
                                if (!_type.GetType().IsPrimitive)
                                {
                                    string _strType = _type.FullName;
                                    MethodInfo[] _methodInfos = _type.GetMethods();


                                    foreach (var item in _methodInfos)
                                    {
                                        if (item.DeclaringType.FullName == _strType)
                                        {


                                            string _strName = item.Name;


                                            string _strReturnType = item.ReturnType.Name;
                                            ListViewItem _listViewItemTem = new ListViewItem(_strReturnType);
                                            _listViewItemTem.SubItems.Add(_strName);
                                            ParameterInfo[] _parameterInfos = item.GetParameters();
                                            string _strParamNames = "";
                                            foreach (var parameter in _parameterInfos)
                                            {


                                                string _strParamName = parameter.ParameterType.Name;
                                                if (!string.IsNullOrEmpty(_strParamNames))
                                                {
                                                    _strParamNames += ",";
                                                }
                                                _strParamNames += _strParamName;




                                            }
                                            _listViewItemTem.SubItems.Add(_strParamNames);
                                            listView1.Items.Add(_listViewItemTem);
                                        }
                                    }
                                }


                            }
                        }
                        catch(Exception)
                        { }
                        
                    }




                }
                else
                {
                    MessageBox.Show("没有找到此名称的网站!");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }


        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string _strHostIp = siteName.Text;


                System.DirectoryServices.DirectoryEntry folderRoot = new DirectoryEntry("IIS://" + _strHostIp + "/W3SVC");
                foreach (System.DirectoryServices.DirectoryEntry item in folderRoot.Children)
                {
                    if (item.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                    {


                        if (item.Properties["ServerComment"].Value.ToString() == "Default Web Site")
                            continue;
                        comboBoxSiteName.Items.Add(item.Properties["ServerComment"].Value.ToString());
                    }
                }
                if (comboBoxSiteName.Items.Count > 0)
                {
                    comboBoxSiteName.SelectedIndex = 0;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
            
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值