当问起如何根据指定的虚拟路径获取此目录相应的物理路径这一问题时,一些朋友经常会给出:使用Server.MapPath”。当然,这绝对是一个正确的回答。不过,它仅仅被限于在可以获取HttpContext的环境中使用。下面我要说的是,在无法获取HttpContext的情况下,如何根据虚拟路径获取相应的物理路径。
  .Net Framework为我们提供了System.DirectoryServices命名空间,以便我们可以简便地访问 Active Directory。当然,我们主要是要使用ADSI(Active Directory 服务接口)来对IIS进行访问。<?XML:NAMESPACE PREFIX = O />

ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
InBlock.gif
/// 获取网站的标识符
InBlock.gif
/// </summary>
InBlock.gif
/// <param name="portNumber">端口号</param>
ExpandedBlockEnd.gif
/// <returns></returns>

None.gifprivate string GetWebSiteIdentifier(string portNumber)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    DirectoryEntry root 
= new DirectoryEntry("IIS://LOCALHOST/W3SVC");
InBlock.gif    
foreach(DirectoryEntry e in root.Children)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
if(e.SchemaClassName == "IIsWebServer")
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
foreach(object property in e.Properties["ServerBindings"])
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if(property.Equals(":" + portNumber + ":"))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return e.Name;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
// 默认为“默认网站”的标识符
InBlock.gif
    return "1";
ExpandedBlockEnd.gif}


  在构造DirectoryEntry时需要提供一个路径,以便将此实例绑定到位于指定路径的 Active Directory 中的节点上。通常情况下,访问IIS时,我们提供的是IIS://LOCALHOST/W3SVC/1/ROOT/YourVirtualDirectoryName。其中,“<?XML:NAMESPACE PREFIX = ST1 />1”是默认网站的标识符,如果指定的虚拟路径不是存在于默认网站中,那么我们也就无法取得到相应的物理路径。为此,我们需要根据虚拟路径中的端口号来获取路径所属网站的标识符,而GetWebSiteIdentifier就实现这个功能的。

ExpandedBlockStart.gifContractedBlock.gif/**//// <summary>
InBlock.gif
/// 获取虚拟目录的物理路径
InBlock.gif
/// </summary>
InBlock.gif
/// <param name="identifier">虚拟目录所属网站的标识符</param>
InBlock.gif
/// <param name="name">虚拟目录名称</param>
ExpandedBlockEnd.gif
/// <returns></returns>

None.gifprivate string GetWebVirtualDirectoryPath(string identifier, string name)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    DirectoryEntry de 
= new DirectoryEntry("IIS://LOCALHOST/W3SVC/" + identifier + "/ROOT/" + name);
InBlock.gif    
string path = (string)de.Properties["Path"].Value;
InBlock.gif
InBlock.gif    
return path;
ExpandedBlockEnd.gif}

  在获取了网站的标识符后,我们就可以去指定虚拟路径的物理路径了。
  P.S. 如果是使用WindowsXP的话,可以直接使用IIS://LOCALHOST/W3SVC/1/ROOT/YourVirtualDirectoryName,因为WindowsXP的IIS不允许使用者创建网站。emsmiled.gif
  希望这个可以对一些朋友有点儿帮助。