最近在做自動安裝BS系統時,遇到需要獲取虛擬目錄對應的物理路徑的問題,稍微整理一下,分享給大家!
///
/// 獲取虛擬目錄對應的物理路徑
///
/// 所在站點端口端口號
/// 虛擬目錄名稱
///
public string GetVirtualDirectory(string _portNumber, string _name)
{
// 獲取網站的標識符,默認爲1
string identifier = null;
DirectoryEntry root = new DirectoryEntry("IIS://LOCALHOST/W3SVC");
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
foreach (object property in e.Properties["ServerBindings"])
{
if (property.Equals(":" + _portNumber + ":"))
{
identifier = e.Name;
break;
}
}
if(identifier != null)
{
break;
}
}
}
if(identifier != null)
{
identifier = "1";
}
DirectoryEntry de = new DirectoryEntry("IIS://LOCALHOST/W3SVC/" + identifier + "/ROOT/" + _name);
string path = (string)de.Properties["Path"].Value;
return path;
}