C#对IIS进行操作的源码

如下的资料是关于C#对IIS进行操作的的代码,希望能对各位有一些用处。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

using System.DirectoryServices;

using System.Security.Principal;

using System.Runtime.InteropServices;

using System.Data;

using System.Configuration;

using System.Web;

namespace IIS_BatchOperate

{

    public class IISHelper

    {

        #region 临时模拟IIS管理员用户

        public const int LOGON32_LOGON_INTERACTIVE = 2;

        public const int LOGON32_PROVIDER_DEFAULT = 0;

        static WindowsImpersonationContext impersonationContext;

        [DllImport("advapi32.dll")]

        public static extern int LogonUserA(String lpszUserName,

            String lpszDomain,

            String lpszPassword,

            int dwLogonType,

            int dwLogonProvider,

            ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]

        public static extern int DuplicateToken(IntPtr hToken,

            int impersonationLevel,

            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]

        public static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

        public static extern bool CloseHandle(IntPtr handle);

        private static bool impersonateValidUser(String userName)

        {

            string domain = "administrator";

            string password = "123";

            WindowsIdentity tempWindowsIdentity;

            IntPtr token = IntPtr.Zero;

            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())

            {

                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,

                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)

                {

                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)

                    {

                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);

                        impersonationContext = tempWindowsIdentity.Impersonate();

                        if (impersonationContext != null)

                        {

                            CloseHandle(token);

                            CloseHandle(tokenDuplicate);

                            return true;

                        }

                    }

                }

            }

            if (token != IntPtr.Zero)

                CloseHandle(token);

            if (tokenDuplicate != IntPtr.Zero)

                CloseHandle(tokenDuplicate);

            return false;

        }

        private static void undoImpersonation()

        {

            impersonationContext.Undo();

        }

        #endregion

        private static int GetWebSiteID(string serverName, string siteName)

        {

            int siteID = -1;

            Regex regex = new Regex(siteName);

            if (serverName.Length < 1)

                serverName = "localhost";

            string tmpStr;

            DirectoryEntry ent = new DirectoryEntry(entPath);

            foreach (DirectoryEntry child in ent.Children)

            {

                if (child.SchemaClassName == "IIsWebServer")

                {

                    if (child.Properties["ServerBindings"].Value != null)

                    {

                        tmpStr = child.Properties["ServerBindings"].Value.ToString();

                        if (regex.Match(tmpStr).Success)

                        {

                            siteID = int.Parse(child.Name);

                            break;

                        }

                    }

                    if (child.Properties["ServerComment"].Value != null)

                    {

                        tmpStr = child.Properties["ServerComment"].Value.ToString();

                        if (regex.Match(tmpStr).Success)

                        {

                            siteID = int.Parse(child.Name);

                            break;

                        }

                    }

                }

            }

            return siteID;

        }

        public static void AddHostHeader(string siteName, string ip, int port, string domain)

        {

            AddHostHeader("localhost", siteName, ip, port, domain);

        }

        public static void AddHostHeader(string serverName, string siteName, string ip, int port, string domain)

        {

            if (impersonateValidUser("dsiis"))

            {

                int siteID = GetWebSiteID(serverName, siteName);

                if (siteID < 1)

                    siteID = 1;

                AddHostHeader(serverName, siteID, ip, port, domain);

                undoImpersonation();

            }

            else

            {

            }

        }

        public static void AddHostHeader(string serverName, int siteid, string ip, int port, string domain)

        {

            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];

            string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);

            if (!serverBindings.Contains(headerStr))

            {

                serverBindings.Add(headerStr);

            }

            site.CommitChanges();

        }

        public static void DeleteHostHeader(string siteName, string ip, int port, string domain)

        {

            DeleteHostHeader("localhost", siteName, ip, port, domain);

        }

        public static void DeleteHostHeader(string serverName, string siteName, string ip, int port, string domain)

        {

            if (impersonateValidUser("dsiis"))

            {

                int siteID = GetWebSiteID(serverName, siteName);

                if (siteID < 1)

                    siteID = 1;

                DeleteHostHeader(serverName, siteID, ip, port, domain);

                undoImpersonation();

            }

            else

            {

            }

        }

        public static void DeleteHostHeader(string serverName, int siteid, string ip, int port, string domain)

        {

            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];

            string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);

            if (serverBindings.Contains(headerStr))

            {

                serverBindings.Remove(headerStr);

            }

            site.CommitChanges();

        }


        public static List LoadIISWebSiteData(string serverName)

        {

            List list = new List();

            int siteID;

            string siteName;

            DirectoryEntry ent = new DirectoryEntry(entPath);

            foreach (DirectoryEntry child in ent.Children)

            {

                string HostName = ConfigurationManager.AppSettings["RencaiHost"].ToString();

                siteName = child.Properties["ServerComment"].Value.ToString();

                if (child.SchemaClassName == "IIsWebServer" && siteName == HostName)

                {

                    siteID = int.Parse(child.Name);

                    list.Add(new IISWebSite(siteID, siteName));

                    HttpCookie Cookie = new HttpCookie("IIsWebServerName");

                    Cookie.Value =siteID.ToString();

                    HttpContext.Current.Response.Cookies.Add(Cookie);

                    break;

                }

            }

            return list;


        }

        public static List LoadHostHeaderList(string serverName, int siteID)

        {

            List list = new List();

            PropertyValueCollection serverBindings = site.Properties["ServerBindings"];

            if (serverBindings != null && serverBindings.Value != null)

            {

                foreach (string str in serverBindings)

                {

                    list.Add(new IISWebSiteHostHeader(siteID, str.Split(':')[0], int.Parse(str.Split(':')[1]), str.Split(':')[2]));

                }

            }

            return list;

        }

        public static bool IsHostHeaderExists(string serverName, IISWebSiteHostHeader newHostHeader)

        {

            bool isFind = false;

            List siteList = LoadIISWebSiteData(serverName);

            foreach (IISWebSite site in siteList)

            {

                List headerList = LoadHostHeaderList(serverName, site.SiteID);

                foreach (IISWebSiteHostHeader header in headerList)

                {

                    if (newHostHeader.Equals(header))

                    {

                        isFind = true;

                        break;

                    }

                }

            }

            return isFind;

        }

        public static List SearchHostHeaderList(string serverName, string hostHeader)

        {

            List list = new List();

            List siteList = LoadIISWebSiteData(serverName);

            foreach (IISWebSite site in siteList)

            {

                List headerList = LoadHostHeaderList(serverName, site.SiteID);

                foreach (IISWebSiteHostHeader header in headerList)

                {

                    if (hostHeader.Equals(header.HostHeader, StringComparison.CurrentCultureIgnoreCase))

                        list.Add(header);

                }

            }

            return list;

        }

    }

    public class IISWebSiteHostHeader

    {

        public int SiteID { get; set; }

        public string IP { get; set; }

        public int Port { get; set; }

        public string HostHeader { get; set; }

        public IISWebSiteHostHeader(int siteID, string ip, int port, string hostHeader)

        {

            this.SiteID = siteID;

            this.IP = ip;

            this.Port = port;

            this.HostHeader = hostHeader;

        }

        public override bool Equals(object obj)

        {

            IISWebSiteHostHeader header = obj as IISWebSiteHostHeader;

            if (header != null)

            {

                if (header.IP == this.IP && header.Port == this.Port && header.HostHeader == this.HostHeader)

                    return true;

                else

                    return false;

            }

            return base.Equals(obj);

        }

    }

    public class IISWebSite

    {

        public int SiteID { get; set; }

        public string SiteName { get; set; }

        public IISWebSite(int siteID, string siteName)

        {

            this.SiteID = siteID;

            this.SiteName = siteName;

        }

    }

}

你可能感兴趣的:(C#对IIS进行操作的源码)