Small Tip One: 根据指定的IIS虚拟路径获取相应的物理路径
  当问起如何根据指定的虚拟路径获取此目录相应的物理路径这一问题时,一些朋友经常会给出:“使用Server.MapPath”。当然,这绝对是一个正确的回答。不过,它仅仅被限于在可以获取HttpContext的环境中使用。下面我要说的是,在无法获取HttpContext的情况下,如何根据虚拟路径获取相应的物理路径。
  .Net Framework为我们提供了System.DirectoryServices命名空间,以便我们可以简便地访问 Active Directory。当然,我们主要是要使用ADSI(Active Directory 服务接口)来对IIS进行访问。
 /// <summary>
/// <summary>
 /// 获取网站的标识符
/// 获取网站的标识符
 /// </summary>
/// </summary>
 /// <param name="portNumber">端口号</param>
/// <param name="portNumber">端口号</param>
 /// <returns></returns>
/// <returns></returns>
 private string GetWebSiteIdentifier(string portNumber)
private string GetWebSiteIdentifier(string portNumber)
 {
{
 DirectoryEntry root = new DirectoryEntry("IIS://LOCALHOST/W3SVC");
    DirectoryEntry root = new DirectoryEntry("IIS://LOCALHOST/W3SVC");
 foreach(DirectoryEntry e in root.Children)
    foreach(DirectoryEntry e in root.Children)
 {
    {
 if(e.SchemaClassName == "IIsWebServer")
        if(e.SchemaClassName == "IIsWebServer")
 {
        {
 foreach(object property in e.Properties["ServerBindings"])
            foreach(object property in e.Properties["ServerBindings"])
 {
            {
 if(property.Equals(":" + portNumber + ":"))
                if(property.Equals(":" + portNumber + ":"))
 {
                {
 return e.Name;
                    return e.Name;
 }
                }
 }
            }
 }
        }
 }
    }
 
 // 默认为“默认网站”的标识符
    // 默认为“默认网站”的标识符
 return "1";
    return "1";
 }
}
       
  在构造DirectoryEntry时需要提供一个路径,以便将此实例绑定到位于指定路径的 Active Directory 中的节点上。通常情况下,访问IIS时,我们提供的是IIS://LOCALHOST/W3SVC/1/ROOT/YourVirtualDirectoryName。其中,“
       
 /// <summary>
/// <summary>
 /// 获取虚拟目录的物理路径
/// 获取虚拟目录的物理路径
 /// </summary>
/// </summary>
 /// <param name="identifier">虚拟目录所属网站的标识符</param>
/// <param name="identifier">虚拟目录所属网站的标识符</param>
 /// <param name="name">虚拟目录名称</param>
/// <param name="name">虚拟目录名称</param>
 /// <returns></returns>
/// <returns></returns>
 private string GetWebVirtualDirectoryPath(string identifier, string name)
private string GetWebVirtualDirectoryPath(string identifier, string name)
 {
{
 DirectoryEntry de = new DirectoryEntry("IIS://LOCALHOST/W3SVC/" + identifier + "/ROOT/" + name);
    DirectoryEntry de = new DirectoryEntry("IIS://LOCALHOST/W3SVC/" + identifier + "/ROOT/" + name);
 string path = (string)de.Properties["Path"].Value;
    string path = (string)de.Properties["Path"].Value;
 
 return path;
    return path;
 }
}
             在获取了网站的标识符后,我们就可以去指定虚拟路径的物理路径了。
  P.S. 如果是使用WindowsXP的话,可以直接使用IIS://LOCALHOST/W3SVC/1/ROOT/YourVirtualDirectoryName,因为WindowsXP的IIS不允许使用者创建网站。 
  希望这个可以对一些朋友有点儿帮助。
       
 
                    
                     
                    
                 
                    
                


 
     
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号