c#根据端口号获取IIS网站物理路径和网站名称

来源:互联网 发布:macbookair下载软件 编辑:程序博客网 时间:2024/06/06 01:09

private const string constIISRoot = "IIS://localhost/w3svc";

        private Hashtable GetWebPathAndWebName(string PortNum)
        {
            Hashtable ht = new Hashtable();
            Regex regex = new Regex(PortNum);
            string tmpStr;
            DirectoryEntry rootIISEntry = new DirectoryEntry(constIISRoot);
            foreach (DirectoryEntry entry in rootIISEntry.Children)
            {
                if (entry.SchemaClassName == "IIsWebServer")
                {
                    if (entry.Properties["ServerBindings"].Value != null)
                    {
                        tmpStr = entry.Properties["ServerBindings"].Value.ToString();
                        if (regex.Match(tmpStr).Success)
                        {
                           ht.Add("name",entry.Properties["ServerComment"].Value.ToString());
                           ht.Add("path", GetWebsitePhysicalPath(entry));
                           break;
                        }
                    }
                }
            }
            return ht;
        }

        /// 得到网站的物理路径
        /// </summary>
        /// <param name="rootEntry">网站节点</param>
        /// <returns></returns>
        public string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
        {
            string physicalPath = "";
            foreach (DirectoryEntry childEntry in rootEntry.Children)
            {
                if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
                {
                    if (childEntry.Properties["Path"].Value != null)
                    {
                        physicalPath = childEntry.Properties["Path"].Value.ToString();
                    }
                    else
                    {
                        physicalPath = "";
                    }
                }
            }
            return physicalPath;
        }

原创粉丝点击