C#中操作IIS 7.0
Microsoft自Windows Vista一起釋出了IIS 7.0,這個已經是去年的話題了,隨後,由.NET開發的Web程式便逐步從IIS 6.0過渡到IIS 7.0上了。IIS 7.0提供了很多比上一版本更多的新特性,包括完全模組化的元件、文字檔案的配置功能、MMC圖形模式管理工具等等,並且與.NET程式語言結合得更加緊密了,在新新增的Microsoft.Web.Administration名稱空間中也增加了很多用於管理和訪問IIS的物件,從而使得通過程式設計方式操作IIS更加簡便。雖然在IIS 6.0時代我們也可以非常輕鬆地通過C#來管理伺服器的IIS,但相對來說,現在需要編寫的程式碼更少,所能完成的功能更強。以下是我在曾經做的一個專案中所寫的一個類庫中的一部分,主要實現了對IIS 7.0的操作,包括建立和刪除站點、建立和刪除虛擬目錄、建立和刪除應用程式池、新增站點預設文件、判斷站點和虛擬目錄是否存在、以及檢查Bindings資訊等。
對於IIS 7.0的介紹讀者如果有興趣的話可以看看下面的兩篇文章,我覺得不錯!
http://blog.joycode.com/scottgu/archive/2007/04/08/100650.aspx
http://msdn.microsoft.com/en-us/magazine/cc163453.aspx
不說廢話了,趕緊貼程式碼吧。
首先是對站點的管理。我寫了一個相對較為通用的私有方法,然後在對外的方法中給出了呼叫介面,包括了建立站點時應用程式池的建立和許可權的管理。
CreateSite
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->///
/// Create a new web site.
///
///
/// "*:<port>:<hostname>" "*:80:myhost.com"
///
public static void CreateSite(string siteName, string bindingInfo,
string physicalPath)
{
createSite(siteName, "http", bindingInfo, physicalPath, true,
siteName + "Pool", ProcessModelIdentityType.NetworkService, null, null, ManagedPipelineMode.Integrated, null);
}
private static void createSite(string siteName, string protocol,
string bindingInformation, string physicalPath,
bool createAppPool, string appPoolName,
ProcessModelIdentityType identityType,
string appPoolUserName, string appPoolPassword,
ManagedPipelineMode appPoolPipelineMode, string
managedRuntimeVersion)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites.Add(siteName, protocol,
bindingInformation, physicalPath);
// PROVISION APPPOOL IF NEEDED
if (createAppPool)
{
ApplicationPool pool = mgr.ApplicationPools.Add
(appPoolName);
if (pool.ProcessModel.IdentityType != identityType)
{
pool.ProcessModel.IdentityType = identityType;
}
if (!String.IsNullOrEmpty(appPoolUserName))
{
pool.ProcessModel.UserName = appPoolUserName;
pool.ProcessModel.Password = appPoolPassword;
}
if (appPoolPipelineMode != pool.ManagedPipelineMode)
{
pool.ManagedPipelineMode = appPoolPipelineMode;
}
site.Applications["/"].ApplicationPoolName = pool.Name;
}
mgr.CommitChanges();
}
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->///
/// Create a new web site.
///
///
/// "*:<port>:<hostname>"
///
public static void CreateSite(string siteName, string bindingInfo,
string physicalPath)
{
createSite(siteName, "http", bindingInfo, physicalPath, true,
siteName + "Pool", ProcessModelIdentityType.NetworkService, null, null, ManagedPipelineMode.Integrated, null);
}
private static void createSite(string siteName, string protocol,
string bindingInformation, string physicalPath,
bool createAppPool, string appPoolName,
ProcessModelIdentityType identityType,
string appPoolUserName, string appPoolPassword,
ManagedPipelineMode appPoolPipelineMode, string
managedRuntimeVersion)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites.Add(siteName, protocol,
bindingInformation, physicalPath);
// PROVISION APPPOOL IF NEEDED
if (createAppPool)
{
ApplicationPool pool = mgr.ApplicationPools.Add
(appPoolName);
if (pool.ProcessModel.IdentityType != identityType)
{
pool.ProcessModel.IdentityType = identityType;
}
if (!String.IsNullOrEmpty(appPoolUserName))
{
pool.ProcessModel.UserName = appPoolUserName;
pool.ProcessModel.Password = appPoolPassword;
}
if (appPoolPipelineMode != pool.ManagedPipelineMode)
{
pool.ManagedPipelineMode = appPoolPipelineMode;
}
site.Applications["/"].ApplicationPoolName = pool.Name;
}
mgr.CommitChanges();
}
}
這個是刪除站點的方法,比較簡單。
DeleteSite
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->///
/// Delete an existent web site.
///
/// Site name.
public static void DeleteSite(string siteName)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
mgr.Sites.Remove(site);
mgr.CommitChanges();
}
}
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->///
/// Delete an existent web site.
///
/// Site name.
public static void DeleteSite(string siteName)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
mgr.Sites.Remove(site);
mgr.CommitChanges();
}
}
}
然後是對虛擬目錄的操作,包括建立和刪除虛擬目錄,都比較簡單。
CreateVDir
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void CreateVDir(string siteName, string vDirName,
string physicalPath)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site == null)
{
throw new ApplicationException(String.Format
("Web site {0} does not exist", siteName));
}
site.Applications.Add("/" + vDirName, physicalPath);
mgr.CommitChanges();
}
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void CreateVDir(string siteName, string vDirName,
string physicalPath)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site == null)
{
throw new ApplicationException(String.Format
("Web site {0} does not exist", siteName));
}
site.Applications.Add("/" + vDirName, physicalPath);
mgr.CommitChanges();
}
}
DeleteVDir
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void DeleteVDir(string siteName, string vDirName)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
Microsoft.Web.Administration.Application app =
site.Applications["/" + vDirName];
if (app != null)
{
site.Applications.Remove(app);
mgr.CommitChanges();
}
}
}
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void DeleteVDir(string siteName, string vDirName)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
Microsoft.Web.Administration.Application app =
site.Applications["/" + vDirName];
if (app != null)
{
site.Applications.Remove(app);
mgr.CommitChanges();
}
}
}
}
刪除應用程式池。
DeletePool
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->///
/// Delete an existent web site app pool.
///
///
App pool name for deletion.
public static void DeletePool(string appPoolName)
{
using (ServerManager mgr = new ServerManager())
{
ApplicationPool pool = mgr.ApplicationPools[appPoolName];
if (pool != null)
{
mgr.ApplicationPools.Remove(pool);
mgr.CommitChanges();
}
}
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->///
/// Delete an existent web site app pool.
///
///
App pool name for deletion.
public static void DeletePool(string appPoolName)
{
using (ServerManager mgr = new ServerManager())
{
ApplicationPool pool = mgr.ApplicationPools[appPoolName];
if (pool != null)
{
mgr.ApplicationPools.Remove(pool);
mgr.CommitChanges();
}
}
}
在站點上新增預設文件。
AddDefaultDocument
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void AddDefaultDocument
(string siteName, string defaultDocName)
{
using (ServerManager mgr = new ServerManager())
{
Configuration cfg = mgr.GetWebConfiguration
(siteName);
ConfigurationSection defaultDocumentSection = cfg.GetSection("system.webServer/defaultDocument");
ConfigurationElement filesElement =
defaultDocumentSection.GetChildElement("files");
ConfigurationElementCollection filesCollection =
filesElement.GetCollection();
foreach (ConfigurationElement elt in filesCollection)
{
if (elt.Attributes["value"].Value.ToString() ==
defaultDocName)
{
return;
}
}
try
{
ConfigurationElement docElement =
filesCollection.CreateElement();
docElement.SetAttributeValue("value", defaultDocName);
filesCollection.Add(docElement);
}
catch (Exception) { } //this will fail if existing
mgr.CommitChanges();
}
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static void AddDefaultDocument
(string siteName, string defaultDocName)
{
using (ServerManager mgr = new ServerManager())
{
Configuration cfg = mgr.GetWebConfiguration
(siteName);
ConfigurationSection defaultDocumentSection = cfg.GetSection("system.webServer/defaultDocument");
ConfigurationElement filesElement =
defaultDocumentSection.GetChildElement("files");
ConfigurationElementCollection filesCollection =
filesElement.GetCollection();
foreach (ConfigurationElement elt in filesCollection)
{
if (elt.Attributes["value"].Value.ToString() ==
defaultDocName)
{
return;
}
}
try
{
ConfigurationElement docElement =
filesCollection.CreateElement();
docElement.SetAttributeValue("value", defaultDocName);
filesCollection.Add(docElement);
}
catch (Exception) { } //this will fail if existing
mgr.CommitChanges();
}
}
檢查虛擬目錄是否存在。
VerifyVirtualPathIsExist
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static bool VerifyVirtualPathIsExist(string siteName, string path)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
foreach (Microsoft.Web.Administration.Application app in site.Applications)
{
if (app.Path.ToUpper().Equals(path.ToUpper()))
{
return true;
}
}
}
}
return false;
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static bool VerifyVirtualPathIsExist(string siteName, string path)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
foreach (Microsoft.Web.Administration.Application app in site.Applications)
{
if (app.Path.ToUpper().Equals(path.ToUpper()))
{
return true;
}
}
}
}
return false;
}
檢查站點是否存在。
VerifyWebSiteIsExist
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static bool VerifyWebSiteIsExist(string siteName)
{
using (ServerManager mgr = new ServerManager())
{
for (int i = 0; i < mgr.Sites.Count; i++)
{
if (mgr.Sites[i].Name.ToUpper().Equals(siteName.ToUpper()))
{
return true;
}
}
}
return false;
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static bool VerifyWebSiteIsExist(string siteName)
{
using (ServerManager mgr = new ServerManager())
{
for (int i = 0; i < mgr.Sites.Count; i++)
{
if (mgr.Sites[i].Name.ToUpper().Equals(siteName.ToUpper()))
{
return true;
}
}
}
return false;
}
檢查Bindings資訊。
VerifyWebSiteBindingsIsExist
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static bool VerifyWebSiteBindingsIsExist(string bindingInfo)
{
string temp = string.Empty;
using (ServerManager mgr = new ServerManager())
{
for (int i = 0; i < mgr.Sites.Count; i++)
{
foreach (Microsoft.Web.Administration.Binding b in mgr.Sites[i].Bindings)
{
temp = b.BindingInformation;
if (temp.IndexOf('*') < 0)
{
temp = "*" + temp;
}
if (temp.Equals(bindingInfo))
{
return true;
}
}
}
}
return false;
}
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->public static bool VerifyWebSiteBindingsIsExist(string bindingInfo)
{
string temp = string.Empty;
using (ServerManager mgr = new ServerManager())
{
for (int i = 0; i < mgr.Sites.Count; i++)
{
foreach (Microsoft.Web.Administration.Binding b in mgr.Sites[i].Bindings)
{
temp = b.BindingInformation;
if (temp.IndexOf('*') < 0)
{
temp = "*" + temp;
}
if (temp.Equals(bindingInfo))
{
return true;
}
}
}
}
return false;
}
以上程式碼均在Windows Vista SP1和Windows Server 2008上測試通過,使用時需要在工程中引用Microsoft.Web.Administration類庫,該類庫為IIS 7.0自帶的。
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-580348/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- IIS 7.0與ASP.NETASP.NET
- IIS 7.0 6大新特性
- 【飲水思源】安裝IIS 7.0
- 操作IIS (轉)
- 也談用在ASP.Net中操作IIS (轉)ASP.NET
- 在C#中操作XML .C#XML
- C# 7.0 語言新特性C#
- 如何實現IIS 7.0對非HTTP協議的支援HTTP協議
- IIS 7.0上用自簽證書來啟用SSL
- C#中PDF文件操作類C#
- C#中URL的操作類C#
- c#中的insert操作C#
- C#中索引器的操作C#索引
- C# 7.0 新特性(3): 模式匹配C#模式
- IIS7.0設定 url重寫成html(偽靜態)HTML
- ASP.NET上傳大檔案報錯,IIS7.0ASP.NET
- 在IIS 7.0上使用自簽證書來啟用SSL
- C# 7.0 新特性(2): 本地方法C#
- C#中幾個不常用的操作符C#
- 透過C#重啟iis網站服務C#網站
- C# 操作ExcelC#Excel
- C#操作ExcelC#Excel
- C# 字串操作C#字串
- [C#]C#中字串的操作C#字串
- [C#]C#時間日期操作C#
- C# BETA2中操作ACCESS資料庫 (轉)C#資料庫
- 關於ASP.NET/C#中對Cookie的操作ASP.NETC#Cookie
- C#操作jsonC#JSON
- C# 操作Excel大全C#Excel
- c#檔案操作C#
- C#操作圖象C#
- C# 檔案操作C#
- C# 操作xml(轉)C#XML
- .NET Core C# 中級篇2-7 檔案操作C#
- C# BETA2中操作ACCESS資料庫(三) (轉)C#資料庫
- C# BETA2中操作ACCESS資料庫(二) (轉)C#資料庫
- C#、IIS獲取時間帶星期問題解決C#
- C#簡單操作MongoDBC#MongoDB