C#列表所有IIS站点以及相关站点属性

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.DirectoryServices;
using System.Reflection;
using System.Text.RegularExpressions;

int TotalServerCount=0;  

   DirectoryEntry rootfolder = new DirectoryEntry("IIS://localhost/W3SVC");
   //TotalServerCount=rootfolder.Children.SchemaFilter.Count;

   foreach (DirectoryEntry child in rootfolder.Children)
   {
    if (child.SchemaClassName == "IIsWebServer")
    {
     TotalServerCount+=1;
    }
   }
   //循环获取所有站点详细属性写入数组中
   string [] arrayServerID = new string[TotalServerCount];//站点标识符
   string [] arrayServerIP = new string[TotalServerCount];//站点主机头
   string [] arrayServerPort = new string[TotalServerCount];//站点主机头
   string [] arrayServerHeader = new string[TotalServerCount];//站点主机头
   string [] arrayServerPath = new string[TotalServerCount];//站点主机头
   string [] arrayServerComment = new string[TotalServerCount];//站点主机头

   string [] arrayServerBinds = new string[TotalServerCount];//站点主机头

   string currentServerBindings;//绑定主机头IP端口字符串
   char[] a=":".ToCharArray();
   string [] currentBingdings =new string[2]; 

   int i=0;
   foreach (DirectoryEntry child in rootfolder.Children)
   {
    if (child.SchemaClassName == "IIsWebServer")
    {
     arrayServerID.SetValue(child.Name.ToString(),i);
     arrayServerComment.SetValue(child.Properties["ServerComment"].Value.ToString(),i);

     currentServerBindings=child.Properties["ServerBindings"].Value.ToString();

     currentBingdings=currentServerBindings.Split(a);

     arrayServerIP.SetValue(currentBingdings[0],i);
     arrayServerPort.SetValue(currentBingdings[1],i);
     arrayServerHeader.SetValue(currentBingdings[2],i);

     foreach (DirectoryEntry rootChild in child.Children)
     {
      if((rootChild.SchemaClassName == "IIsWebVirtualDir")&&(rootChild.Name.ToString()=="root"))
      {
       if(rootChild.Properties["Path"].Value==null)
       {
        arrayServerPath.SetValue("",i);
       }
       else
       {
        arrayServerPath.SetValue(rootChild.Properties["Path"].Value.ToString(),i);
       }
      }
     }

     i+=1;
    }
   }

   //写入到datagrid中去
   //循环从数组中读取数据
   for(i=0;i<TotalServerCount;i++)
   {

    listView1.Items.Add((i+1).ToString());
    listView1.Items[i].SubItems.Add(arrayServerID.GetValue(i).ToString());
    listView1.Items[i].SubItems.Add(arrayServerComment.GetValue(i).ToString());
    listView1.Items[i].SubItems.Add(arrayServerIP.GetValue(i).ToString());
    listView1.Items[i].SubItems.Add(arrayServerPort.GetValue(i).ToString());
    listView1.Items[i].SubItems.Add(arrayServerHeader.GetValue(i).ToString());
    listView1.Items[i].SubItems.Add(arrayServerPath.GetValue(i).ToString());

   } 
public class IISManager
    {
        string strServer = "localhost";
        string strWebSiteID = "1";
        string strWebSiteName = string.Empty;
        string strVirtualPath = string.Empty;

        public string Server
        {
            get { return strServer; }
            set { strServer = value; }
        }
        public string WebSiteID
        {
            get { return strWebSiteID; }
            set { strWebSiteID = value; }
        }
        public string WebSiteName
        {
            get { return strWebSiteName; }
            set { strWebSiteName = value; }
        }
        public string VirtualPath
        {
            get { return strVirtualPath; }
            set { strVirtualPath = value; }
        }

        public IISManager()
        {
        }

        public IISManager(string strS, string strW)
        {
            strServer = strS;
            strWebSiteID = strW;
        }

        public string GetConfigAllFilePath()
        {
            DirectoryEntry rootEntry = new DirectoryEntry("IIS://" + strServer + "/w3svc/" + strWebSiteID + "/root");

            string strTempPath = string.Empty;
            foreach (DirectoryEntry de in rootEntry.Children)
            {
                if (de.Name == "kintera_com")
                {
                    strTempPath = de.Properties["path"][0].ToString();
                    break;
                }
            }
            strTempPath = strTempPath.Substring(0, strTempPath.Length - 12);
            return strTempPath + @"\CommonLib\includes\INC_config_all.asp";
        }

        public void CreateWebSite()
        {
            DirectoryEntry root = new DirectoryEntry("IIS://" + this.Server + "/W3SVC");

            if (!EnsureNewSiteAvaible(this.Server))
            {
                throw(new Exception("The Web Site existed!"));
            }
            else
            {
                DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", this.WebSiteID);

                site.Invoke("Put", "ServerComment", this.WebSiteName);
                site.Invoke("Put", "KeyType", "IIsWebServer");
                site.Invoke("Put", "ServerBindings", this.Server);
                site.Invoke("Put", "ServerState", 2);
                site.Invoke("Put", "FrontPageWeb", 1);
                site.Invoke("Put", "DefaultDoc", "index.aspx,index.html,index.html,default.aspx,default.htm,default.html");
                site.Invoke("Put", "ServerAutoStart", 1);
                site.Invoke("Put", "ServerSize", 1);
                site.Invoke("SetInfo");
            }
        }

        public void CreateVirtualFolder()
        {
            DirectoryEntry site = new DirectoryEntry("IIS://" + this.Server + "/W3SVC" + this.WebSiteID + "/root");

            DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");

            siteVDir.Properties["AppIsolated"][0] = 2;

            siteVDir.Properties["Path"][0] = this.VirtualPath;

            siteVDir.Properties["AccessFlags"][0] = 513;

            siteVDir.Properties["FrontPageWeb"][0] = 1;

            siteVDir.Properties["AppRoot"][0] = "/W3SVC/" + this.WebSiteID + "/Root";

            siteVDir.Properties["AppFriendlyName"][0] = "ROOT";

            siteVDir.CommitChanges();

            site.CommitChanges();
        }

        public bool EnsureNewSiteAvaible(string bindStr)
        {
            string strDePath = String.Format("IIS://{0}/w3svc", this.Server);

            DirectoryEntry de = new DirectoryEntry(strDePath);
            foreach (DirectoryEntry child in de.Children)
            {
                if (child.SchemaClassName == "IIsWebServer")
                {
                    if (child.Properties["ServerBindings"].Value != null)
                    {
                        if (child.Properties["ServerBindings"].Value.ToString() == bindStr)
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        public void DeleteWebSiteByName(string siteName)
        {
            string siteNum = GetWebSiteNum(siteName);

            string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", this.Server, siteNum);

            DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);

            string rootPath = String.Format("IIS://{0}/w3svc", this.Server);

            DirectoryEntry rootEntry = new DirectoryEntry(rootPath);

            rootEntry.Children.Remove(siteEntry);

            rootEntry.CommitChanges();
        }

        public void DeleteWebSiteByName()
        {
            string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", this.Server,this.WebSiteID);

            DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);

            string rootPath = String.Format("IIS://{0}/w3svc", this.Server);

            DirectoryEntry rootEntry = new DirectoryEntry(rootPath);

            rootEntry.Children.Remove(siteEntry);

            rootEntry.CommitChanges();
        }

        public void StartWebSite(string siteName)
        {
            string siteNum = GetWebSiteNum(siteName);

            string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", this.Server, siteNum);

            DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);

            siteEntry.Invoke("Start", new object[] { });
        }

        public void StartWebSite()
        {
            string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", this.Server,this.WebSiteID);

            DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);

            siteEntry.Invoke("Start", new object[] { });
        }

        public void StopWebSite(string siteName)
        {
            string siteNum = GetWebSiteNum(siteName);

            string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", this.Server, siteNum);

            DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);

            siteEntry.Invoke("Stop", new object[] { });
        }

        public void StopWebSite()
        {
            string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", this.Server, this.WebSiteID);

            DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);

            siteEntry.Invoke("Stop", new object[] { });
        }

        public string GetWebSiteNum(string siteName)
        {
            Regex regex = new Regex(siteName);
            string tmpStr;
            string rootPath = String.Format("IIS://{0}/w3svc", this.Server);

            DirectoryEntry deEntry = new DirectoryEntry(rootPath);

            foreach (DirectoryEntry child in deEntry.Children)
            {
                if (child.SchemaClassName == "IIsWebServer")
                {
                    if (child.Properties["ServerBindings"].Value != null)
                    {
                        tmpStr = child.Properties["ServerBindings"].Value.ToString();

                        if (regex.Match(tmpStr).Success)
                        {
                            return child.Name;
                        }
                    }

                    if (child.Properties["ServerComment"].Value != null)
                    {
                        tmpStr = child.Properties["ServerComment"].Value.ToString();

                        if (regex.Match(tmpStr).Success)
                        {
                            return child.Name;
                        }
                    }
                }
            }
            return "No WebSite";
        }

        public void ResetIIS()
        {
            Process.Start("iisreset");
        }

        public void StopIIS()
        {
            ServiceController sc = new ServiceController("iisadmin");
            if (sc.Status == ServiceControllerStatus.Running)
            {
                sc.Stop();
            }
            //Process.Start("cmd.exe", "/start iisreset");
        }

        public void StartIIS()
        {
            ServiceController sc = new ServiceController("iisadmin");
            sc.Start();
        }
    } 
public List<string> EnumWebSite()
  {
  string strDePath = String.Format("IIS://{0}/w3svc", this.Server);
  DirectoryEntry de = new DirectoryEntry(strDePath);
  List<string> list=new List<string>();
  foreach (DirectoryEntry child in de.Children)
  {
  if (child.SchemaClassName == "IIsWebServer")
  {
  list.Add(child.Properties["ServerComment"].Value.ToString());
  }
  }
  } 
            // C# 获取网站的 IIS 站点名称 ,获取站点当前连接数
            string siteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
            System.Management.ManagementObject o = new System.Management.ManagementObject("Win32_PerfFormattedData_W3SVC_WebService.Name=siteName");
            Response.Write(o.Properties["CurrentConnections"].Value.ToString());
<p>服务器IP:<%=Request.ServerVariables["LOCAL_ADDR"]%></p>
<p>服务器名:<%=Request.ServerVariables["SERVER_NAME"]%></p>
<p> HTTP端口:<%=Request.ServerVariables["SERVER_PORT"]%></p>
<p> 服务器时间:<%=DateTime .Now%></p>
<p> 操作系统信息:<%=Request.ServerVariables["HTTP_USER_AGENT"]%></p>
<p> 允许文件:<%=Request.ServerVariables["HTTP_ACCEPT"]%></p>
<p> 虚拟目录:<%=HttpContext.Current.Request.ApplicationPath%></p>
<p> 物理路径:<%=HttpRuntime.AppDomainAppPath%></p>
<p> 探针文件路径:<%=Context.Server.MapPath(Request.ServerVariables["SCRIPT_NAME"])%></p>
<p> 脚本超时时间:<%=Server.ScriptTimeout%>(秒)</p>
<p> CPU个数: <%=Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS")%></p>

String serverOS = Environment.OSVersion.ToString();
String CpuSum = Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS");// CPU个数:
String CpuType = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER");// CPU类型:
String ServerSoft = Request.ServerVariables["SERVER_SOFTWARE"]; // 信息服务软件:
String MachineName = Server.MachineName;// 服务器名
String ServerName = Request.ServerVariables["SERVER_NAME"];// 服务器域名
String ServerPath = Request.ServerVariables["APPL_PHYSICAL_PATH"];// 虚拟服务绝对路径
String ServerNet = ".NET CLR " + Environment.Version.ToString(); // DotNET 版本
String ServerArea = (DateTime.Now - DateTime.UtcNow).TotalHours > 0 ? "+" + (DateTime.Now -DateTime.UtcNow).TotalHours.ToString() : (DateTime.Now - DateTime.UtcNow).TotalHours.ToString();// 服务器时区
String ServerTimeOut = Server.ScriptTimeout.ToString(); // 脚本超时时间
String ServerStart = ((Double)System.Environment.TickCount / 3600000).ToString("N2");// 开机运行时长
// AspNet CPU时间
String ServerSessions = Session.Contents.Count.ToString();// Session总数
String ServerApp = Application.Contents.Count.ToString(); // Application总数
String ServerCache = Cache.Count.ToString(); //应用程序缓存总数
// 应用程序占用内存
// String ServerFso = Check("Scripting.FileSystemObject"); // FSO 文本文件读写
String ServerTimeOut = Server.ScriptTimeout.ToString() + "毫秒"; // 本页执行时间

HTTP_USER_AGENT 获得用户使用的浏览器类型和版本

REMOTE_ADDR 获取用户的IP地址

REQUEST_METHOD 获取请求的方法

LOCAL_ADDR 获取服务器IP地址

SERVER_NAME 获取服务器主机名

PATH_INFO 获取当前执行程序的虚拟路径

PATH_TRANSLATED 获取当前执行程序的绝对路径

CONTENT_LENGTH 获取请求程序所发送内容的字符总数

CONTENT_TYPE 获取请求的信息类型

GATEWAY_INTERFACE 获取网关接口

QUERY_STRING 获取URL的附加信息

SCRIPT_NAME 获取当前程序的文件名(包含虚拟路径)

SERVER_PORT 获取服务器接受请求的端口

SERVER_PROTOCOL 获取服务器遵从的协议以及版本号

HTTP_ACCEPT_LANGUAGE 获取用户所使用的语言

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AdminLogin_Default : System.Web.UI.Page
{
#region 必需的设计器变量
protected string MemberName, AdminLevel;
protected string ServerOS, CpuSum, CpuType, ServerSoft, MachineName, ServerName, ServerPath, ServerNet, ServerArea, ServerTimeOut, ServerStart;
protected string PrStart, AspNetN, AspNetCpu, ServerSessions, ServerApp, ServerCache, ServerAppN, ServerFso, RunTime;
#endregion

protected void Page_Load(object sender, EventArgs e)
{
DataLoad();
}

#region 获取服务器及用户信息
private void DataLoad()
{
DateTime sTime = DateTime.Now;

ServerOS = Environment.OSVersion.ToString(); //操作系统:
CpuSum = Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"); //CPU个数:
CpuType = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER"); //CPU类型:
ServerSoft = Request.ServerVariables["SERVER_SOFTWARE"]; //信息服务软件:
MachineName = Server.MachineName; //服务器名
ServerName = Request.ServerVariables["SERVER_NAME"]; //服务器域名
ServerPath = Request.ServerVariables["APPL_PHYSICAL_PATH"]; //虚拟服务绝对路径
ServerNet = ".NET CLR " + Environment.Version.ToString(); //DotNET 版本
ServerArea = (DateTime.Now - DateTime.UtcNow).TotalHours > 0 ? "+" + (DateTime.Now - DateTime.UtcNow).TotalHours.ToString() : (DateTime.Now - DateTime.UtcNow).TotalHours.ToString(); //服务器时区
ServerTimeOut = Server.ScriptTimeout.ToString(); //脚本超时时间
ServerStart = ((Double)System.Environment.TickCount / 3600000).ToString("N2"); //开机运行时长
PrStart = GetPrStart(); //进程开始时间
AspNetN = GetAspNetN(); //AspNet 内存占用
AspNetCpu = GetAspNetCpu(); //AspNet CPU时间
ServerSessions = Session.Contents.Count.ToString(); //Session总数
ServerApp = Application.Contents.Count.ToString(); //Application总数
ServerCache = Cache.Count.ToString(); //应用程序缓存总数
ServerAppN = GetServerAppN(); //应用程序占用内存
ServerFso = Check("Scripting.FileSystemObject"); //FSO 文本文件读写
ServerTimeOut = Server.ScriptTimeout.ToString() + "毫秒"; //本页执行时间
if (ServerSoft == "")
{
ServerSoft = "无";
}

#region 页面初始化必需的内容
Header.Title = "沉紫龙" + " - 系统管理";
//HeaderTextInfo.Initialization();
//HeaderTextInfo.GetAdminHeader(this, null);
#endregion

#region WebControls Config
// ViewState Config
this.EnableViewState = false;
#endregion

//执行时间
DateTime eTime = DateTime.Now;
RunTime = ((eTime - sTime).TotalMilliseconds).ToString();
}
#endregion

#region 获取服务器系统信息
private string GetServerAppN()
{
string temp;
try
{
temp = ((Double)GC.GetTotalMemory(false) / 1048576).ToString("N2") + "M";
}
catch
{
temp = "未知";
}
return temp;
}

private string GetAspNetN()
{
string temp;
try
{
temp = ((Double)System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + "M";
}
catch
{
temp = "未知";
}
return temp;
}

private string GetAspNetCpu()
{
string temp;
try
{
temp = ((TimeSpan)System.Diagnostics.Process.GetCurrentProcess().TotalProcessorTime).TotalSeconds.ToString("N0");
}
catch
{
temp = "未知";
}
return temp;
}

private string GetPrStart()
{
string temp;
try
{
temp = System.Diagnostics.Process.GetCurrentProcess().StartTime.ToString();
}
catch
{
temp = "未知";
}
return temp;
}

private string Check(string obj)
{
try
{
object claobj = Server.CreateObject(obj);
return "支持";
}
catch
{
return "不支持";
}
}
#endregion
}
时间: 2024-08-23 00:56:17

C#列表所有IIS站点以及相关站点属性的相关文章

大数据服务相关站点整理

今天突然来了兴致,想要看看目前有哪些大数据服务相关站点,百度'大数据'翻了十来页,找出了以下站点,[xxx(分类)]是我根据其网站性质定义的标签,如有不妥之处,勿喷. 资讯类: 中国大数据资料和交流中心,[大数据资讯.大数据论坛] http://www.thebigdata.cn/ 紫数网,大数据服务平台,大数据门户[大数据资讯.问答社区] http://www.zishu010.com/ 36大数据,专注大数据应用与商业:[大数据资讯] http://www.36dsj.com/ 大数据中国,

在 IIS 上创建 FTP 站点

微软参考文档: 在 IIS 上生成 FTP 站点 主要过程: 1.控制面板 -> 程序 -> 启动或关闭Windows功能 -> 将Internet Information Services全部勾选 此步骤是为系统添加IIS.FTP功能 2.控制面板 -> 系统和安全 -> 管理工具 -> IIS -> 打开IIS管理工具之后参考下面图例 至此,完成创建FTP,之后需要配置FTP 3.FTP防火墙支持 至此,FTP已经创建并配置成功,其他特别的配置,需要用户自己按

优秀的相关站点留存-不定时更新

集团站点 1. 站点名:IMPORTNEW 网址:http://www.importnew.com/ 简单介绍:专注分享JAVA技术 2. 站点名:PHP100 网址:http://www.php100.com/ 简单介绍:专注于分享传递PHP学习 3. 站点名:极客范 网址:http://www.geekfan.net/ 简单介绍:致力于分享前沿与新兴科技应用 4. 站点名:恩聪PHP 网址:http://php.ncong.com/ 简单介绍:一个系统学习PHP的站点 5. 站点名:PHP手

《今天你买到票了吗?——从铁道部12306.cn站点漫谈电子商务站点的“海量事务快速处理”系统》

<今天你买到票了吗?--从铁道部12306.cn站点漫谈电子商务站点的"海量事务快速处理"系统> 首发地址: http://bbs.hpx-party.org/thread-8488-1-1.html .一万四千字电子商务站点干货贴,贯穿产品.研发.运维三大领域,没有耐心读完的读者慎入,另外,本文不是教你怎样订到车票的. 相关文章: 不能简单套用"实物电商系统"对"大型票务系统"做需求分析 "大型票务系统"和&qu

站点权重对于站点的重要性

你要好好的思考,及其在百度更接近完美的时候就更要做好这些,事实上这些都是影响用户体会的要素.一个成功的站点能够说它在收取利益的同一时候也在帮助用户.如今说说站点权重有何重要性呢?事实上搜索引擎给站点(包括页面)赋予一定的威望值,对站点(含页面)威望的评价,一个站点权重越高,在搜索引擎所占的价值成分就越好,在搜索引擎排行就越好.一个站点在搜索引擎中的权重是件非常艰难的工作,由于种种要素的搅扰,影响了咱们正确的断定,事实上能够非常好的利用站点权重去做优化. 一用户投票 用户投票是用户对你站点的惬意度

17Exchange Server 2010跨站点部署-AD站点规划部署

10.AD站点部署 10.1 创建站点 默认情况下,创建第一个AD的时候,会自动生成一个名为Default-First-Site-Name的站点,如下图所示 为了便于后续的管理,我这里更改默认的站点名称为GZ-Site 之前在讲到配置CAS Array的时候,已经提到,站点关联到阵列后,以后更新重命名站点,阵列内容也会更新 使用Get-ClientAccessArray查看当前阵列所对定的站点信息,可以看到更新到了GZ-Site 下面新增一个站点,使用dssite.msc命令或者在管理工具中打开

站点构架是站点制作的重中之重

我的站点的图片我差点儿都是用ps处理过的,站点制作构架,我们都知道.无论后面的网址生成了什么,前台和后台对接好之后,当我在网页上加入图片或表格时.优化CSS CSS叠层样式表让网页载入起来更高效,我在站点首页改动时一些样式代码直接写进去了,代码有些冗余了.假设有能力自己做出一个比較安全的文章公布系统,当然也能够手动的添加关键词链接,不简单明了内容更新少. 事实上是能够在后台布置我们的关键词的,那么怎么设计布局呢?首先,扁平式的结构就是全部的页面都放在站点的根文件夹下. 由于这样便于维护和管理,所

利用Appserv搭建多个站点(多站点配置)

AppServ 是 PHP 网站开发的一个工具包,包含Apache .PHP .MySQL.我们在开发网站时,经常是在本地开发完成后,然后上传到服务,所有会用到多站点配置,怎么利用Appserv搭建多个站点(多站点配置). 1.下载appserv,可以到官方网站下载,百度直接搜索Appserv就可以,打开后点击DOWNLOAD按钮,现在最新版是8.4.0. 2.安装appserv,这里需要注意的是,在安装过程中可以选择安装哪些,可以根据需要安装. 3.修改hosts文件. 打开 windows\

5.链接相关的属性以及其他属性

链接相关的属性: 1.为a与area元素增加了media属性.download属性以及ping属性,其中media属性规定目标URL是为什么类型的媒介/设备进行优化的,download属性用于让用户下载目标链接所指向的资源,而不是直接打开该目标资源,这些属性均只能在href属性存在时使用. 2.为area元素增加了hreflang属性与rel属性,以保持与a元素.link元素的一致. 3.为link元素增加了新属性sizes,该属性可以与icon元素结合使用(通过rel属性),该属性指定关联图标