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
}

 

转载于:https://www.cnblogs.com/hnsongbiao/p/7435731.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值