日期:2018-04-14  浏览次数:3460 次

  using System.DirectoryServices;
         using System.Reflection;
       

        /// <summary>
        /// 设置ip地址和域访问权限
        /// </summary>
        /// <Author>刘海明 2011-07-19</Author>
        /// <param name="strVirtualPath">虚拟目录路径</param>
        /// <param name="strIp">要设置的ip地址</param>
        /// <returns>操作成功返回true,否则返回false</returns>
        public static bool SetIPGrant(string strVirtualPath, string strIp)
        {
            try
            {
                string strGrant = "IPGrant";

                System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strVirtualPath);

                Type objType = IIS.Properties["IPSecurity"][0].GetType();
                object IPSecurity = IIS.Properties["IPSecurity"][0];

                Array origIPDenyList = (Array)objType.InvokeMember("IPDeny", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);

                bool bGrantByDefault = (bool)objType.InvokeMember("GrantByDefault", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);

                if (bGrantByDefault)
                {
                    objType.InvokeMember("GrantByDefault", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, IPSecurity, new object[] { false });
                }

                object[] newIPDenyList = new object[1];
                newIPDenyList[0] = strIp;

                objType.InvokeMember(strGrant, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, IPSecurity, new object[] { newIPDenyList });
                IIS.Properties["IPSecurity"][0] = IPSecurity;

                IIS.CommitChanges();
                IIS.RefreshCache();

                return true;
            }
            catch
            {
                return false;
            }
        }

 

        //调用:

        string strVirPath = "IIS:///W3SVC/1/ROOT/ArcGIS/REST";
        string strVirIp = "192.168.5.159";
        SetIPGrant(strVirPath, strVirIp, strIPGrant);