首先要對Microsoft.Web.Administration進行引用,它主要是用來操作IIS7;
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:建立應用程式集區 (對程式池的設定主要是針對IIS7;IIS7應用程式集區託管模式主要包括整合跟傳統模式,並進行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#代碼來對IIS7程式池託管管道模式及版本進行修改;
5:針對IIS6的NET版進行設定;因為此處我是用到NET4.0所以V4.0.30319 若是NET2.0則在這進行修改 v2.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進行操作的代碼;相容IIS6及IIS7;建立虛擬目錄並對相應的屬性進行設定;對IIS7還進行建立程式池的程式;並設定程式池的配置;
複製代碼 代碼如下:/// <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);
}