C\#IIS 프로그램 풀 및 사이트 생 성 설정 구현 코드 조작

13884 단어 C#IIS 프로그램 풀
먼저 Microsoft.Web.Administration 을 인용 해 야 합 니 다.주로 IIS 7 을 조작 하 는 데 사 용 됩 니 다.
using System.DirectoryServices;using Microsoft.Web.Administration;
1:우선 이 버 전의 IIS 버 전 을 설정 합 니 다.

DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            string Version = getEntity.Properties["MajorIISVersionNumber"].Value.ToString();
            MessageBox.Show("IIS :" + Version);
2:판단 프로그램 풀 이 존재 합 니 다.

/// <summary>
        ///
        /// </summary>
        /// <param name="AppPoolName"> </param>
        /// <returns>true false </returns>
        private bool IsAppPoolName(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    result = true;
                }
            }
            return result;
        }
3:응용 프로그램 풀 삭제

/// <summary>
        ///
        /// </summary>
        /// <param name="AppPoolName"> </param>
        /// <returns>true false </returns>
        private bool DeleteAppPool(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    try
                    {
                        getdir.DeleteTree();
                        result = true;
                    }
                    catch
                    {
                        result = false;
                    }
                }
            }
            return result;
        }
4:응용 프로그램 풀 을 만 듭 니 다.(프로그램 풀 에 대한 설정 은 주로 IIS 7 을 대상 으로 합 니 다.IIS 7 응용 프로그램 풀 위탁 관리 모델 은 주로 통합 과 고전 모델 을 포함 하고 NET 버 전의 설정 을 실시한다)

string AppPoolName = "LamAppPool";
            if (!IsAppPoolName(AppPoolName))
            {
                DirectoryEntry newpool;
                DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
                newpool.CommitChanges();
                MessageBox.Show(AppPoolName + " ");
            }
            #endregion

            #region ( NET )
            ServerManager sm = new ServerManager();
            sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
            sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; // Integrated Classic
            sm.CommitChanges();
            MessageBox.Show(AppPoolName + " :" + sm.ApplicationPools[AppPoolName].ManagedPipelineMode.ToString() + " NET :" + sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion);

C\#코드 를 사용 하여 IIS 7 프로그램 탱크 위탁 관리 파이프 모드 와 버 전 을 수정 합 니 다
5:IIS 6 의 NET 버 전 을 설정 합 니 다.여기 서 는 NET 4.0 을 사용 하기 때문에 V 4.0.30319 NET 2.0 이 라면 여기 서 v 2.0.50727 을 수정 합 니 다.

// aspnet_regiis.exe
            string fileName = Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf("W3SVC");
            path = path.Remove(0, index);
            // ASPnet_iis.exe ,
            startInfo.Arguments = "-s " + path;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            string errors = process.StandardError.ReadToEnd();
6:평소에 우 리 는 IIS 의 MIME 유형 을 증가 시 켜 야 할 수도 있 습 니 다.다음은 주로 우리 가 사용 하 는 두 가지 유형 은 xaml,xap 이다.

IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
            NewMime.Extension = ".xaml"; NewMime.MimeType = "application/xaml+xml";
            IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            TwoMime.Extension = ".xap"; TwoMime.MimeType = "application/x-silverlight-app";
            rootEntry.Properties["MimeMap"].Add(NewMime);
            rootEntry.Properties["MimeMap"].Add(TwoMime);
            rootEntry.CommitChanges();
7:다음은 설치 할 때 IIS 를 조작 하 는 코드 입 니 다.IIS 6 및 IIS 7 호 환;새 가상 디 렉 터 리 를 만 들 고 해당 속성 을 설정 합 니 다.IIS 7 에 새 프로그램 풀 을 만 드 는 프로그램 도 진행 합 니 다.프로그램 풀 설정 하기;

/// <summary>
    ///
    /// </summary>
    /// <param name="siteInfo"></param>
      public  void CreateNewWebSite(NewWebSiteInfo siteInfo)
        {
            if (!EnsureNewSiteEnavaible(siteInfo.BindString))
            {
                throw new Exception(" " + Environment.NewLine + siteInfo.BindString);
            }
            DirectoryEntry rootEntry = GetDirectoryEntry(entPath);

            newSiteNum = GetNewWebSiteID();
            DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, "IIsWebServer");
            newSiteEntry.CommitChanges();

            newSiteEntry.Properties["ServerBindings"].Value = siteInfo.BindString;
            newSiteEntry.Properties["ServerComment"].Value = siteInfo.CommentOfWebSite;
            newSiteEntry.CommitChanges();
            DirectoryEntry vdEntry = newSiteEntry.Children.Add("root", "IIsWebVirtualDir");
            vdEntry.CommitChanges();
            string ChangWebPath = siteInfo.WebPath.Trim().Remove(siteInfo.WebPath.Trim().LastIndexOf('\\'),1);
            vdEntry.Properties["Path"].Value = ChangWebPath;


            vdEntry.Invoke("AppCreate", true);//

            vdEntry.Properties["AccessRead"][0] = true; //
            vdEntry.Properties["AccessWrite"][0] = true;
            vdEntry.Properties["AccessScript"][0] = true;//
            vdEntry.Properties["AccessExecute"][0] = false;
            vdEntry.Properties["DefaultDoc"][0] = "Login.aspx";//
            vdEntry.Properties["AppFriendlyName"][0] = "LabManager"; //           
            vdEntry.Properties["AuthFlags"][0] = 1;//0 ,1 3 ,7 windows
            vdEntry.CommitChanges();

            // MIME
            //IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
            //NewMime.Extension = ".xaml"; NewMime.MimeType = "application/xaml+xml";
            //IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            //TwoMime.Extension = ".xap"; TwoMime.MimeType = "application/x-silverlight-app";
            //rootEntry.Properties["MimeMap"].Add(NewMime);
            //rootEntry.Properties["MimeMap"].Add(TwoMime);
            //rootEntry.CommitChanges();

            #region IIS7
            DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            int Version =int.Parse(getEntity.Properties["MajorIISVersionNumber"].Value.ToString());
            if (Version > 6)
            {
                #region
                string AppPoolName = "LabManager";
                if (!IsAppPoolName(AppPoolName))
                {
                    DirectoryEntry newpool;
                    DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                    newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
                    newpool.CommitChanges();
                }
                #endregion

                #region ( NET )
                ServerManager sm = new ServerManager();
                sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
                sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; // Integrated Classic
                sm.CommitChanges();
                #endregion

                vdEntry.Properties["AppPoolId"].Value = AppPoolName;
                vdEntry.CommitChanges();
            }
            #endregion


            // aspnet_regiis.exe
            string fileName = Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf("W3SVC");
            path = path.Remove(0, index);
            // ASPnet_iis.exe ,
            startInfo.Arguments = "-s " + path;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            string errors = process.StandardError.ReadToEnd();
            if (errors != string.Empty)
            {
                throw new Exception(errors);
            }

        }


string entPath = String.Format("IIS://{0}/w3svc", "localhost");

public  DirectoryEntry GetDirectoryEntry(string entPath)
       {
           DirectoryEntry ent = new DirectoryEntry(entPath);
           return ent;
       }

        public class NewWebSiteInfo
        {
            private string hostIP;   // IP
            private string portNum;   //
            private string descOfWebSite; // 。 。 "www.dns.com.cn"
            private string commentOfWebSite;// 。 。
            private string webPath;   // 。 "e:\ mp"

            public NewWebSiteInfo(string hostIP, string portNum, string descOfWebSite, string commentOfWebSite, string webPath)
            {
                this.hostIP = hostIP;
                this.portNum = portNum;
                this.descOfWebSite = descOfWebSite;
                this.commentOfWebSite = commentOfWebSite;
                this.webPath = webPath;
            }

            public string BindString
            {
                get
                {
                    return String.Format("{0}:{1}:{2}", hostIP, portNum, descOfWebSite); // (IP, , )
                }
            }

            public string PortNum
            {
                get
                {
                    return portNum;
                }
            }

            public string CommentOfWebSite
            {
                get
                {
                    return commentOfWebSite;
                }
            }

            public string WebPath
            {
                get
                {
                    return webPath;
                }
            }
        }

8:아래 코드 는 폴 더 권한 을 설정 하 는 것 입 니 다.아래 코드 는 Everyone 을 만 들 고 모든 권한 을 부여 하 는 것 입 니 다.

/// <summary>
        /// EVERONE
        /// </summary>
        /// <param name="FileAdd"> </param>
        public void SetFileRole()
        {
            string FileAdd = this.Context.Parameters["installdir"].ToString();
            FileAdd = FileAdd.Remove(FileAdd.LastIndexOf('\\'), 1);
            DirectorySecurity fSec = new DirectorySecurity();
            fSec.AddAccessRule(new FileSystemAccessRule("Everyone",FileSystemRights.FullControl,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow));
            System.IO.Directory.SetAccessControl(FileAdd, fSec);
        }

좋은 웹페이지 즐겨찾기