woyoudn 发表于 2015-8-16 13:18:27

如何用C#删除IIS中的站点和虚拟目录

如何用C#删除IIS中的站点
  //删除虚拟目录是这样的   
public   static   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   
{   
DirectoryEntry   deVDir   =   new   DirectoryEntry("IIS://localhost/W3SVC/"   +   SiteID   +   "/ROOT");   
deRoot.RefreshCache();   
deVDir   =   new   DirectoryEntry("IIS://localhost/W3SVC/"   +   SiteID   +   "/ROOT");   
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   static   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).Split(new   char[]   {':'});   
hostname   =   srvBindings.Trim();   
   
//判断,可换用hostname   
//if   (WebSiteName   ==   bb.Properties["ServerComment"].Value.ToString())   SiteID=bb.Name;   
if   (WebSiteName   ==   hostname)   SiteID=bb.Name;   
//   Clear   Variable   
hostname   =   "";   
}   
catch{}   
}   
if   (SiteID   ==   null)   return   null;   
return   SiteID;   
}   
catch   
{   
return   null;   
}   
}   
   
   
//这是删除删除站点的方法!
  ///   <summary>   
///   删除站点   
///   </summary>   
///   <param   name="WebSiteName">站点名</param>   
///   <returns>成功或失败信息!</returns>   
public   static   string   DelSite(string   WebSiteName)   
{   
try   
{   
string   SiteID   =   GetSiteID(WebSiteName);   
if   (SiteID   ==   null)   return   "error:该站点不存在.";   
   
DirectoryEntry   deRoot=   new   DirectoryEntry("IIS://localhost/W3SVC");   
try   
{   
DirectoryEntry   deVDir   =new   DirectoryEntry();   
deRoot.RefreshCache();   
deVDir   =   deRoot.Children.Find(SiteID,   "IIsWebServer");   
deRoot.Children.Remove(deVDir);   
   
deRoot.CommitChanges();   
deRoot.Close();   
return   "successful:删除站点"   +   WebSiteName   +   "成功!";   
}   
catch   (System.Exception)   
{   
return   "error:该站点不存在.";   
}   
}   
catch(Exception   e)   
{   
return   "error:删除站点失败."   +   e.Message;   
}   
}
//DirectoryEntry   deVDir=deRoot.Children.Find(SiteID,   "IIsWebServer");   //这是关键

引用自:http://blog.ofo.cn/Trackback.aspx?id=578
页: [1]
查看完整版本: 如何用C#删除IIS中的站点和虚拟目录