c#操作IIS站点

时间:2023-03-09 21:30:06
c#操作IIS站点

/// <summary>
/// 获取本地IIS版本
/// </summary>
/// <returns></returns>
public string GetIIsVersion()
{
try
{
DirectoryEntry entry = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
string version = entry.Properties["MajorIISVersionNumber"].Value.ToString();
return version;
}
catch (Exception se)
{
//说明一点:IIS5.0中没有(int)entry.Properties["MajorIISVersionNumber"].Value;属性,将抛出异常 证明版本为 5.0
return string.Empty;
}
}

/// <summary>
/// 创建虚拟目录网站
/// </summary>
/// <param name="webSiteName">网站名称</param>
/// <param name="physicalPath">物理路径</param>
/// <param name="domainPort">站点+端口,如192.168.1.23:90</param>
/// <param name="isCreateAppPool">是否创建新的应用程序池</param>
/// <returns></returns>
public int CreateWebSite(string webSiteName, string physicalPath, string domainPort, bool isCreateAppPool)
{
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
// 为新WEB站点查找一个未使用的ID
int siteID = 1;
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
int ID = Convert.ToInt32(e.Name);
if (ID >= siteID) { siteID = ID + 1; }
}
}
// 创建WEB站点
DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
site.Invoke("Put", "ServerComment", webSiteName);
site.Invoke("Put", "KeyType", "IIsWebServer");
site.Invoke("Put", "ServerBindings", domainPort + ":");
site.Invoke("Put", "ServerState", 2);
site.Invoke("Put", "FrontPageWeb", 1);
site.Invoke("Put", "DefaultDoc", "Default.html");
site.Invoke("Put", "ServerAutoStart", 1);
site.Invoke("Put", "ServerSize", 1);
site.Invoke("SetInfo");
// 创建应用程序虚拟目录
DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
siteVDir.Properties["AppIsolated"][0] = 2;
siteVDir.Properties["Path"][0] = physicalPath;
siteVDir.Properties["AccessFlags"][0] = 513;
siteVDir.Properties["FrontPageWeb"][0] = 1;
siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";
siteVDir.Properties["AppFriendlyName"][0] = "Root";

if (isCreateAppPool)
{
DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");

DirectoryEntry newpool = apppools.Children.Add(webSiteName, "IIsApplicationPool");
newpool.Properties["AppPoolIdentityType"][0] = "4"; //4
newpool.Properties["ManagedPipelineMode"][0] = "0"; //0:集成模式 1:经典模式
newpool.CommitChanges();
siteVDir.Properties["AppPoolId"][0] = webSiteName;
}

siteVDir.CommitChanges();
site.CommitChanges();
return siteID;
}

/// <summary>
/// 得到网站的物理路径
/// </summary>
/// <param name="rootEntry">网站节点</param>
/// <returns></returns>
public static 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;
}

/// <summary>
/// 获取站点列表
/// </summary>
public static List<IISInfo> GetServerBindings()
{
List<IISInfo> iisList = new List<IISInfo>();
string entPath = String.Format("IIS://localhost/w3svc");
DirectoryEntry ent = new DirectoryEntry(entPath);
foreach (DirectoryEntry child in ent.Children)
{
if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
{
if (child.Properties["ServerBindings"].Value != null)
{
object objectArr = child.Properties["ServerBindings"].Value;
string serverBindingStr = string.Empty;
if (IsArray(objectArr))//如果有多个绑定站点时
{
object[] objectToArr = (object[])objectArr;
serverBindingStr = objectToArr[0].ToString();
}
else//只有一个绑定站点
{
serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
}
IISInfo iisInfo = new IISInfo();
iisInfo.siteNum = child.Name;//站点编号
iisInfo.SiteName = child.Properties["ServerComment"].Value.ToString();//站点名称
iisInfo.DomainPort = serverBindingStr;//绑定
iisInfo.AppPool = child.Children.Find("Root", "IISWebVirtualDir").Properties["AppPoolId"].Value.ToString();//应用程序池名称
DirectoryEntry siteEntry = new DirectoryEntry(String.Format("IIS://localhost/w3svc/{0}", child.Name));
iisInfo.SitePath = GetWebsitePhysicalPath(siteEntry);//获取站点路径
iisList.Add(iisInfo);

}
}
}
return iisList;
}
public static string GetServerBindingsString()//返回拼接字符串
{
string result = "";
string entPath = String.Format("IIS://localhost/w3svc");
DirectoryEntry ent = new DirectoryEntry(entPath);
foreach (DirectoryEntry child in ent.Children)
{
if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
{
if (child.Properties["ServerBindings"].Value != null)
{
object objectArr = child.Properties["ServerBindings"].Value;
string serverBindingStr = string.Empty;
if (IsArray(objectArr))//如果有多个绑定站点时
{
object[] objectToArr = (object[])objectArr;
serverBindingStr = objectToArr[0].ToString();
}
else//只有一个绑定站点
{
serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
}

DirectoryEntry siteEntry = new DirectoryEntry(String.Format("IIS://localhost/w3svc/{0}", child.Name));

result += child.Name + "," + child.Properties["ServerComment"].Value.ToString() + "," + serverBindingStr + "," + child.Children.Find("Root", "IISWebVirtualDir").Properties["AppPoolId"].Value.ToString() + "," + GetWebsitePhysicalPath(siteEntry) + ";";

}
}
}
return result;
}
/// <summary>
/// 创建应用池
/// </summary>
/// <param name="appPoolName"></param>
/// <param name="Username"></param>
/// <param name="Password"></param>
/// <returns></returns>
public bool CreateAppPool(string appPoolName, string Username, string Password)
{
bool issucess = false;
try
{
//创建一个新程序池
DirectoryEntry newpool;
DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");

//设置属性 访问用户名和密码 一般采取默认方式
newpool.Properties["WAMUserName"][0] = Username;
newpool.Properties["WAMUserPass"][0] = Password;
newpool.Properties["AppPoolIdentityType"][0] = "3";
newpool.CommitChanges();
issucess = true;
return issucess;
}
catch // (Exception ex)
{
return false;
}
}
public void CreateAppPool(string AppPoolName)
{
if (!IsAppPoolName(AppPoolName))
{
DirectoryEntry newpool;
DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
newpool.CommitChanges();
MessageBox.Show(AppPoolName + "程序池增加成功");
}

////修改应用程序的配置(包含托管模式及其NET运行版本)
//ServerManager sm = new ServerManager();
//sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
//sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成 Classic为经典
//sm.CommitChanges();
//MessageBox.Show(AppPoolName + "程序池托管管道模式:" + sm.ApplicationPools[AppPoolName].ManagedPipelineMode.ToString() + "运行的NET版本为:" + sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion);
}
/// <summary>
/// 判断程序池是否存在
/// </summary>
/// <param name="AppPoolName">程序池名称</param>
/// <returns>true存在 false不存在</returns>
private bool IsAppPoolName(string AppPoolName)
{
bool result = false;
DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
foreach (DirectoryEntry getdir in appPools.Children)
{
if (getdir.Name.Equals(AppPoolName))
{
result = true;
}
}
return result;
}

/// <summary>
/// 获取应用池列表
/// </summary>
/// <returns>应用池列表</returns>
public string AppPoolNameList()
{
string list = "";
DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
foreach (DirectoryEntry getdir in appPools.Children)
{
list += getdir.Name + ",";//应用池名称
}
if (list != "")
{
list = list.Substring(0, list.Length - 1);
}
return list;
}
/// <summary>
/// 根据站点名称查询对应应用池名称
/// </summary>
/// <param name="siteName"></param>
/// <returns></returns>
public string AppPoolNameBySiteName(string siteName)
{
string AppPoolName = "";
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry website in root.Children)
{
if (website.SchemaClassName != "IIsWebServer") continue;
string comment = website.Properties["ServerComment"][0].ToString();
if (comment == siteName)
{
DirectoryEntry siteVDir = website.Children.Find("Root", "IISWebVirtualDir");
AppPoolName = siteVDir.Properties["AppPoolId"][0].ToString();

return AppPoolName;
}
}

return string.Empty;
}
/// <summary>
/// 建立程序池后关联相应应用程序及虚拟目录
/// </summary>
public void SetAppToPool(string appname, string poolName)
{
//获取目录
DirectoryEntry getdir = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry getentity in getdir.Children)
{
if (getentity.SchemaClassName.Equals("IIsWebServer"))
{
//设置应用程序程序池 先获得应用程序 在设定应用程序程序池
//第一次测试根目录
foreach (DirectoryEntry getchild in getentity.Children)
{
if (getchild.SchemaClassName.Equals("IIsWebVirtualDir"))
{
//找到指定的虚拟目录.
foreach (DirectoryEntry getsite in getchild.Children)
{
if (getsite.Name.Equals(appname))
{
//【测试成功通过】
getsite.Properties["AppPoolId"].Value = poolName;
getsite.CommitChanges();
}
}
}
}
}
}
}

/// <summary>
/// 已知路径删除站点目录文件
/// </summary>
/// <param name="sitepath">网站路径</param>
public string DeleteSiteFile(string sitepath) //void DeleteSiteFile(string siteName)
{
try
{
Directory.Delete(sitepath, true);
return "删除站点成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 根据站点名称删除站点目录文件
/// </summary>
/// <param name="siteName">网站路径</param>
public string DeleteSiteFileBySiteName(string siteName)
{
try
{
string siteNum = GetWebSiteNum(siteName);
DirectoryEntry siteEntry = new DirectoryEntry(String.Format("IIS://localhost/w3svc/{0}", siteNum));
string sitePath = GetWebsitePhysicalPath(siteEntry);//获取站点路径
DirectoryInfo dir = new DirectoryInfo(sitePath);
if (dir.Exists)
{
Directory.Delete(sitePath, true);
}
return "删除站点成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 获取网站编号
/// </summary>
/// <param name="siteName"></param>
/// <returns></returns>
public string GetWebSiteNum(string siteName)
{
Regex regex = new Regex(siteName);
string tmpStr;
DirectoryEntry ent = new DirectoryEntry("IIS://localhost/w3svc");

foreach (DirectoryEntry child in ent.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;
}
}
}
}

throw new Exception("没有找到我们想要的站点" + siteName);
}
/// <summary>
/// 获取网站编号
/// </summary>
private string getWebSiteNum(string siteName)
{
using (DirectoryEntry ent = new DirectoryEntry("IIS://localhost/w3svc"))
{
foreach (DirectoryEntry child in ent.Children)
{
if (child.SchemaClassName == "IIsWebServer")
{
if (child.Properties["ServerComment"].Value != null)
{
string tmpStr = child.Properties["ServerComment"].Value.ToString();
if (tmpStr.Equals(siteName))
{
return child.Name;
}
}
}
}
}
return string.Empty;
}

static Hashtable hs = new Hashtable();//创建哈希表,保存池中的站点
static string[] pls;//池数组
static string[] nums;//应用程序池中各自包含的网站数量

/// <summary>
/// 判断网站名与应用程序池名称是否相等
/// </summary>
/// <param name="wnames">网站名称</param>
/// <returns>相等为假</returns>
public bool chname(string wnames)
{
bool ctf = true;
pls = AppPoolNameList().Split(',');
foreach (string i in pls)
{
if (wnames == i)
ctf = false;
else ctf = true;
}
return ctf;
}

/// <summary>
/// 获得池数组对应的网站数量
/// </summary>
public void WebNums()
{
List<string> weblist = new List<string>();
pls = AppPoolNameList().Split(',');
foreach (string i in pls)
{
if (hs[i].ToString() != "")
weblist.Add(hs[i].ToString().Split(',').Length.ToString());
else
weblist.Add("0");
}
nums = weblist.ToArray();

}
/// <summary>
/// 移动网站到新池
/// </summary>
/// <param name="webns">网站名称</param>
/// <param name="poolold">旧池名称</param>
/// <param name="poolns">新池名称</param>
public void movepool(string webns, string poolold, string poolns)
{
pls = AppPoolNameList().Split(',');
try
{
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry website in root.Children)
{
if (website.SchemaClassName != "IIsWebServer") continue;
string comment = website.Properties["ServerComment"][0].ToString();
if (comment == webns)
{
DirectoryEntry siteVDir = website.Children.Find("Root", "IISWebVirtualDir");
siteVDir.Invoke("Put", new object[2] { "AppPoolId", poolns });
siteVDir.CommitChanges();
website.Invoke("Put", new object[2] { "AppPoolId", poolns });
website.CommitChanges();
}
}
for (int i = 0; i < pls.Length; i++)//遍历旧池并修改原数目数组的数据
{
if (pls[i] == poolold)
{
nums[i] = (int.Parse(nums[i]) - 1).ToString();
string[] h = hs[poolold].ToString().Split(',');
string hnew = "";
foreach (string s in h)
if (s != webns)
{
if (hnew == "")
hnew = s;
else hnew += "," + s;
}
hs[poolold] = hnew;
if (hs[poolns].ToString() == "") hs[poolns] = webns;
else hs[poolns] += "," + webns;
}
if (pls[i] == poolns)
{
WebNums();
nums[i] = (int.Parse(nums[i]) + 1).ToString();
}
}
}
catch (Exception ex)
{

Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 应用池操作
/// </summary>
/// <param name="AppPoolName">应用池名称</param>
/// Start开启 Recycle回收 Stop 停止
/// <returns></returns>
public string AppPoolOP(string AppPoolName, string state)
{
try
{

DirectoryEntry appPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
DirectoryEntry findPool = appPool.Children.Find(AppPoolName, "IIsApplicationPool");
findPool.Invoke(state, null);
appPool.CommitChanges();
appPool.Close();
return "操作成功";

}

catch (Exception ex)
{
return "操作失败";

}
}

/// <summary>
/// 判断object对象是否为数组
/// </summary>
public static bool IsArray(object o)
{
return o is Array;
}