程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 使用ASP.NET來管理IIS

使用ASP.NET來管理IIS

編輯:.NET實例教程

使用ASP.Net來操作IIS,可以達到創建虛擬目錄,虛擬站點,刪除虛擬目錄,列表等等功能.
關鍵:ASP.Net的用戶權限不足以操作IIS,要授予一個高點的權限.
 方法1,在web.config文件中加入這一行<identity impersonate="true" />,不過有風險.
 方法2,使用假冒,我就是用這一方法,但還是有風險,
 其它方法,略

using System;
using System.IO;
using System.DirectoryServices;

namespace com.todayisp.IISmanager
{
 /// <summary>
 /// Summary description for IISManager.
 /// </summary>
 public class IISManager
 {
  private DirectoryEntry _IISServer;
  //public int Counter = 10; //限制創建虛擬目錄數量

  //創建一個虛擬目錄
  public string CreateVDir(string WebSiteName,string nameDirectory,int Counter)
  {

   string SiteID = GetSiteID(WebSiteName);
   if (SiteID == null) return "error:該站點不存在.";

   _iisServer = new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID);
   try
   {
    DirectoryEntry Web = _iisServer.Children.Find("Root","IISWebVirtualDir");
    DirectoryEntry VD = Web.Children.Find(nameDirectory,"IISWebVirtualDir");
    return "error:你要建立的虛擬目錄已經存在.";
   }
   catch
   {
    try
    {
     DirectoryEntry folderRoot = _iisServer.Children.Find("Root","IISWebVirtualDir");

     int Thecount=0;
     foreach(DirectoryEntry b1 in folderRoot.Children)
     {
      Thecount = Thecount + 1;
     }

     //如果虛擬目錄數量沒超過指定數量,則創建.
     if (Thecount < Counter)
     {
      string ThePath;
      ThePath=folderRoot.PropertIEs["Path"].Value +"\\" + nameDirectory;

      //如果沒有該目錄,則創建一個真實目錄
      DirectoryInfo di = Directory.CreateDirectory(ThePath);

      DirectoryEntry newVirDir = folderRoot.Children.Add(nameDirectory,"IISWebVirtualDir");
      newVirDir.CommitChanges();
      // Set PropertIEs
      newVirDir.PropertIEs["AccessRead"].Add(true);
      newVirDir.PropertIEs["Path"].Value = ThePath;
      //Create a Application;Don't use invoke method
      // Save Changes
      newVirDir.CommitChanges();
      folderRoot.CommitChanges();
      _IISServer.CommitChanges();
      newVirDir.Invoke("AppCreate",true);
      return "successful:你已經成功地創建了一個虛擬目錄:" + nameDirectory;
     }
     else
     {
      return "error:你的站點的虛擬目錄已經滿" + Counter + "個,所以不能再創建.";
     }
    }
    catch(Exception e)
    {
     return "error:嘗試進入該站點失敗." + e.Message;
    }
   }
   
  }

  //刪除虛擬目錄
  public string DelVirtualDirectory(string WebSiteName,string nameDirectory)
  {
   try
   {
    string SiteID = GetSiteID(WebSiteName);
    if (SiteID == null) return "error:該站點不存在.";

    
    DirectoryEntry deRoot= new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID + "/ROOT");
    try
    {
 &nbsp;   DirectoryEntry deVDir = deRoot.Children.Find(nameDirectory, "IISWebVirtualDir");
     deRoot.RefreshCache();
     deVDir = deRoot.Children.Find(nameDirectory, "IISWebVirtualDir");
     deVDir.Invoke("AppDelete", null);
     deRoot.Children.Remove(deVDir);
     deRoot.CommitChanges();
     deRoot.Close();
     return "successful:刪除虛擬目錄" + nameDirectory + "成功!";
    }
    catch
    {
     return "error:該虛擬目錄不存在.";
    }
   }
   catch(Exception e)
   {
    return "error:刪除目錄失敗." + e.Message;
   }
>  }

  //查找對應的虛擬站點.
  public string GetSiteID(string WebSiteName)
  {
   DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
   try
   {
    string SiteID= null;
    string hostname;
    foreach(DirectoryEntry bb in root.Children)
    {
     try
     {
      //if(Convert.ToInt32(bb.Name.Trim()) < 0) continue;
      PropertyValueCollection pvc = bb.PropertIEs["ServerBindings"];

      String[] srvBindings = ((string)pvc[0]).Split(new char[] {':'});
      hostname = srvBindings[2].Trim();

      //判斷,可換用hostname
      //if (WebSiteName == bb.PropertIEs["ServerComment"].Value.ToString()) SiteID=bb.Name; 
      if (WebSiteName == hostname) SiteID=bb.Name;
   &nbsp;  // Clear Variable
      hostname = "";
     }
     catch{}
    }
    if (SiteID == null) return null;
    return SiteID;
   }
   catch
   {
    return null;
   }
  }

  //虛擬目錄重命名
  public bool RenameVirtualDirectory(string WebSiteName,string nameDirectory,string NewName)
  {
   try
   {
    DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
    
    string SiteID="";
    string hostname;
    foreach(DirectoryEntry bb in root.Children)
    {
     try
     {
      //if(Convert.ToInt32(bb.Name.Trim()) < 0) continue;
      PropertyValueCollection pvc = bb.PropertIEs["ServerBindings"];
      String[] srvBindings = ((string)pvc[0]).Split(new char[] {':'});
      hostname = srvBindings[2].Trim();
      if(hostname.Equals("")) hostname = "localhost";

      //判斷,可換用hostname
      //if (WebSiteName == bb.PropertIEs["ServerComment"].Value.ToString()) SiteID=bb.Name; 
      if (WebSiteName == hostname) SiteID=bb.Name;
      // Clear Variable
      hostname = "";
     }
     catch{}
    }
    
    DirectoryEntry deRoot= new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID + "/ROOT"

;);
    DirectoryEntry deVDir = deRoot.Children.Find(nameDirectory, "IISWebVirtualDir");
    deRoot.RefreshCache();
    deVDir = deRoot.Children.Find(nameDirectory, "IISWebVirtualDir");
    deVDir.Rename("yeah");
    deRoot.CommitChanges();
    deRoot.Close();
    return true;
   }
   catch
   {
    return false;
   }
  }


  //創建虛擬站點的類,需要輸入"站點名","站點根目錄對應地址","端口".
  public bool CreateWebSite(string siteName,string Path,string Port)
  {
   try
   {
    DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
    // Find unused ID value for new web site
    int siteID = 1;
    foreach(DirectoryEntry ef in root.Children)
    {
     if(ef.ScheMaclassName == "IISWebServer")
     {
      int ID = Convert.ToInt32(ef.Name);
      if(ID >= siteID)
      {
       siteID = ID+1;
      }
     }
    }// Create web site
    DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IISWebServer", siteID);
    site.Invoke("Put", "ServerComment", siteName);
    site.Invoke("Put", "KeyType", "IISWebServer");
    site.Invoke("Put", "ServerBindings", ":" + Port + ":");
    site.Invoke("Put", "ServerState", 2);
    site.Invoke("Put","FrontPageWeb", 1);
    site.Invoke("Put", "DefaultDoc", "Default.ASPx");
    site.Invoke("Put", "SecureBindings", ":443:");
    site.Invoke("Put", "ServerAutoStart", 1);
    site.Invoke("Put", "ServerSize", 1);
    site.Invoke("SetInfo");
    // Create application virtual
    DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
    siteVDir.PropertIEs["AppIsolated"][0] = 2;
    siteVDir.PropertIEs["Path"][0] = Path;
    siteVDir.PropertIEs["AccessFlags"][0] = 513;
    siteVDir.PropertIEs["FrontPageWeb"][0] = 1;
    siteVDir.PropertIEs["AppRoot"][0] = "/LM/W3SVC/"+siteID+"/Root";
    siteVDir.Properties["AppFrIEndlyName"][0] = "Root";
    siteVDir.CommitChanges();
    site.CommitChanges();
    return true;
   }
   catch
   {
   return false;
   }
  }


  //對虛擬站點的虛擬目錄列表
  public string DirAll(string WebSiteName,string VDirName,string Path)
  {
   DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
    
   string SiteID="";
   string hostname;
   foreach(DirectoryEntry bb in root.Children)
   {
    try
    {
     //if(Convert.ToInt32(bb.Name.Trim()) < 0) continue;
     PropertyValueCollection pvc = bb.PropertIEs["ServerBindings"];
     String[] srvBindings = ((string)pvc[0]).Split(new char[] {':'});
     hostname = srvBindings[2].Trim();
     if(hostname.Equals("")) hostname = "localhost";

     //判斷,可換用hostname
     //if (WebSiteName == bb.PropertIEs["ServerComment"].Value.ToString()) SiteID=bb.Name; 
     if (WebSiteName == hostname) SiteID=bb.Name;
     // Clear Variable
     hostname = "";
    }
    catch{}
   }

   DirectoryEntry deRoot= new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID + "/ROOT");

   if (VDirName == null)
   {
    string RealPath = deRoot.PropertIEs["Path"].Value.ToString();
    string VPath = deRoot.Path;
    try
    {
     string AllDir = "";
     string cc = "<br>";

     foreach(DirectoryEntry a in deRoot.Children)
     {
      AllDir = AllDir + "<a href=?sitename=" + WebSiteName + "&vdir=" + a.Name + ">" + a.Name + "<br>";
     }
     DirectoryInfo di = new DirectoryInfo(RealPath);
     DirectoryInfo[] subdirectoryEntries = di.GetDirectorIEs();
     foreach(DirectoryInfo subdirectory in subdirectoryEntrIEs)
     {
      cc = cc + subdirectory.Name + "<br>";
     }

     

     return AllDir;
    }
    catch
    {
    }


    return "END";
   }
   else
   {
    DirectoryEntry subRoot = deRoot.Children.Find(VDirName,"IISWebVirtualDir");
    string RealPath = subRoot.PropertIEs["Path"].Value.ToString() + "\\" + Path + "\\";
    try
    {
     string cc = "<br>";
     string filename = "<br>";


     DirectoryInfo di = new DirectoryInfo(RealPath);
 DirectoryInfo[] subdirectoryEntries = di.GetDirectorIEs();
     foreach(DirectoryInfo subdirectory in subdirectoryEntrIEs)
     {
      cc = cc + "<a href='?sitename=" + WebSiteName + "&VDir=" + VDirName + "&Path=" + Path + @"\" + subdirectory.Name + "'>" + subdirectory.Name + "</a><br>";
     }

     // Create an array representing the files in the current directory.
     FileInfo[] fi = di.GetFiles();
     foreach (FileInfo fiTemp in fi)
     {
      filename = filename + fiTemp.Name + "<br>";
     }

     return cc + filename;
    }
    catch
    {
     return "NO" + Path;
    }
    
   }
  }


 }
}

使用方法如下: 在IISManager.ASPx文件中

<%@ Page language="c#" AutoEventWireup="false"%>
//<%@ Import Namespace= "com.todayisp.identity"%>
<%@ Import Namespace= "com.todayisp.IISmanager"%>
<%
string WebSite = Request.Params["WebSite"];
string VDir = Request.Params["VDir"];
string ManageType = Request.Params["ManageType"];
int Counter = 2; //限制創建虛擬目錄數量
//string UserName = Request.Params["UserName"];
//string Password = Request.Params["PassWord"];

if (WebSite == null && VDir == null)
{
 Response.Write("error:請輸入站點名或目錄名.");
 return;
}

//這部分為使用了RSA加密的解密方法
/*if (UserName == null && PassWord == null)
{
 Response.Write("error:用戶名和密碼為空.");
 return;
}

try
{
 IDEN Key = new IDEN();
 string PasswordKey = Key.ChangeKey(PassWord);
 if (PassWordKey == null) return;
}*/

try
 { /*
  //假冒身份開始
  IDEN Identity = new IDEN();
  bool In = Identity.ChangeRoleIN(UserName,PassWordKey);
  if (!In){
   Response.Write("error:變更用戶權限失敗");
   return;
  }*/

  IISManager isMang = new IISManager();
  string test="";
  switch(ManageType)
  {
   case "Del":
    test = isMang.DelVirtualDirectory(WebSite,VDir);
    break;
   case "Create":
    test = isMang.CreateVDir(WebSite,VDir,Counter);
    break;
   default:
    Response.Write("error:沒有選定操作類型.");
    break;
  }
  

  Response.Write(test);
  /*
  //假冒身份結束
  Identity.ChangeRoleOUT();
  */
 }
catch(Exception e){
  Response.Write("error:" + e.Message);
}

%>

 

今天整理代碼的時候發現一直對母版頁內ContentPlaceHolder的引用,使用的控件查找方式:


程序代碼 程序代碼

this.Master.FindControl("SideBarBox") as ContentPlaceHolder


這樣做的原理大概就是通過在母版頁內查找控件ID,然後通過反射進行調用的。反射本身就是極其影響效率的一種方式,特別是在頁面訪問量特別大的時候,不做緩存處理,那麼對於服務器來說是一場噩夢。雖然還有生成靜態頁面的方法,但是現在談的是如何使用強類型引用母版頁子控件。

於是開始做實驗,首先在母版頁聲明:



程序代碼 程序代碼

public static ContentPlaceHolder sideBarBox;


然後在protected void Page_Load(object sender, EventArgs e)裡面將頁面的ContentPlaceHolder引用給sideBarBox。結果運行出錯,沒有給對象賦值。

仔細想了一下,估計是子頁的Page_Load比母版頁的Page_Load要先處理,所以導致為空。看了一下MSDN,確實是這樣的,頁面的加載順序如下:


  • 母版頁控件 Init 事件。
  • 內容控件 Init 事件。
  • 母版頁 Init 事件。
  • 內容頁 Init 事件。
  • 內容頁 Load 事件。
  • 母版頁 Load 事件。
  • 內容控件 Load 事件。
  • 內容頁 PreRender 事件。
  • 母版頁 PreRender 事件。
  • 母版頁控件 PreRender 事件。
  • 內容控件 PreRender 事件。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved