C#操作iis(安装包操作IIS以及属性介绍)
安装包操作IIS的代码实例:
#regio
rivate void CreateVirtualDir()
{
try
{
tring constIISWebSiteRoot = "IIS://" + iis + "/W3SVC/1/ROOT"
DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot)
DirectoryEntry newRoot = root.Children.Add(port, root.SchemaClassName)
ewRoot.Properties["Path"][0] = dir; //传来参数的目录地址
ewRoot.Properties["AppIsolated"][0] = 2; // 值 0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池
ewRoot.Properties["AccessScript"][0] = true; // 可执行脚本
ewRoot.Properties["AccessWrite"][0] = true
ewRoot.Invoke("AppCreate", true)
ewRoot.Properties["DefaultDoc"][0] = "Default.aspx";//设置起始页
ewRoot.Properties["AppFriendlyName"][0] = port; // 传来参数的应用程序名
ewRoot.CommitChanges()
root.CommitChanges()
tring fileName = Environment.GetEnvironmentVariable("windir") + @"/Microsoft.NET/Framework/v4.0.30319/aspnet_regiis.exe"
ProcessStartInfo startInfo = new ProcessStartInfo(fileName)
//处理目录路径
tring path = newRoot.Path.ToUpper()
int index = path.IndexOf("W3SVC")
ath = path.Remove(0, index)
//启动aspnet_iis.exe程序,刷新教本映射
tartInfo.Arguments = "-s " + path
tartInfo.WindowStyle = ProcessWindowStyle.Hidde
tartInfo.UseShellExecute = false
tartInfo.CreateNoWindow = true
tartInfo.RedirectStandardOutput = true
tartInfo.RedirectStandardError = true
Process process = new Process()
rocess.StartInfo = startInfo
rocess.Start()
rocess.WaitForExit()
tring errors = process.StandardError.ReadToEnd()
if (errors != string.Empty)
throw new Exception(errors)
}
catch (Exception ee)
{
MessageBox.Show("虚拟目录创建失败!您可以手动创建! " + ee.Message, "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0)
}
}
#endregio
.Net中需要使用ADSI来操作IIS
System.DirectoryServices命名空间--DirectoryEntry //在.net组件中 System.DirectoryServices.dll
了解IIS元数据(Metabase)的层次结构,每一个节点称之Key,而每个Key可以包含一或多个值,这些值就是我们说的属性(properties)
IIS元数据中的Key与IIS中的元素是相符的,因此元数据中的属性值的设定是会影响IIS中的设置。
Schema 指每个结点的类型
IIsVirtualDir 虚拟目录
IIsWebDir 普通目录
.. 文件
//创建虚拟目录
DirectoryEntry--目录入口。使用过ADSI的人都知道操作IIS时,需要提供他们的Path
这个Path的格式为: IIS://ComputerName/Service/Website/Directory
ComputerName :即操作的服务器的名字,可以是名字也可以是IP,经常用的就是localhost
Service :即操作的服务器 如:
W3SVC We
MSFTPSVC FTP
SMTP
WebSite:站点标识,设置操作的站点。是一个数字,默认站点是1,如果有其它,则从1始依次类推。
Directory:目录名称,顶层目录为"ROOT",其它目录则是(Child)
1.首先我们获取一个站点的顶层目录(根目录):
DirectoryEntry rootfolder = new DirectoryEntry("IIS://localhost/W3SVC/1/ROOT")
如果我们创建这个对象是没有发生异常,则表示这个目录是真实存在的。
2.添加新的虚拟目录,比如我们要加的是"目录名":
虚拟目录名 目录类型(Schema)
DirectoryEntry newVirDir = rootfolder.Children.Add("目录名","IIsWebVirtualDir")
ewVirDir.Invoke("AppCreate",true); //调用ADSI中的"AppCreate"方法将目录真正创建
ewVirDir.CommitChanges(); //最后便是依次调用新、根目录的CommitChanges方法,确认此次操作。
rootfolder.CommitChanges()
//建议大家最好是先创建目录,然后再赋值,即更新目录信息。
3.更新虚拟目录
了解IIS中一些重要的设置
(AccessRead) 可读
(AccessWrite) 可写
(AccessExecute) 执行
这些都可通过DirectoryEntry.Properties属性集合的赋值来实现。赋值可以通过两种方式来完成:
第一种是调用Properties集合的Add方法,如:
dir.Properties["AccessRead"].Add(true)
第二种是对第一个索引值赋值:
dir.Properties["AccessRead"][0] = true
这两种方法都是可行的。具体是要看你的喜好了。
在进行赋值之前我们还是要确定要要赋值的目标吧:)这里我们使用DirectoryEntries.Find方法,如:
DirectoryEntry de = rootfolder.Children.Find("目录名","IIsVirtualDir")
找到了,我们就可以赋值了。赋值时一定要好好看看啊,虚拟目录的属性值可以超多,一查一大堆。。
比较常用的有:AccessRead,AccessWrite,AccessExecute,AccessScript,DefaultDoc,EnableDefaultDoc,Path
4.删除虚拟目录
删除虚拟目录的方法也很简单,就是找到你要删除的虚拟目录,然后调用AppDelete方法。
DirectoryEntry de = rootfolder.Children.Find("Aspcn","IIsVirtualDir")
de.Invoke("AppDelete",true)
rootfolder.CommitChanges()
还有一种方法,就是调用Root目录的Delete方法。
object[] paras = new object[2]
aras[0] = "IIsWebVirtualDir"; //表示操作的是虚拟目录
aras[1] = "Aspcn"
rootfolder.Invoke("Delete",paras)
rootfolder.CommitChanges()
asp.net(C#)操作IIS源代码,创建站点,管理虚拟目录等
using System
using System.DirectoryService
using System.Collectio
using System.Text.RegularExpressio
using System.Text
amespace QF
{
ublic class IIS
{
#region UserName,Password,HostName的定义
ublic static string HostName
{
get
{
return hostName
}
et
{
hostName = value
}
}
ublic static string UserName
{
get
{
return userName
}
et
{
userName = value
}
}
ublic static string Password
{
get
{
return password
}
et
{
if(UserName.Length <= 1)
{
throw new ArgumentException("还没有指定好用户名。请先指定用户名")
}
assword = value
}
}
ublic static void RemoteConfig(string hostName, string userName, string password)
{
HostName = hostName
UserName = userName
Password = password
}
rivate static string hostName = "localhost"
rivate static string userName = "qf"
rivate static string password = "qinfei"
#endregio
#region 根据路径构造Entry的方法
/// <summary>
/// 根据是否有用户名来判断是否是远程服务器。
/// 然后再构造出不同的DirectoryEntry出来
/// </summary>
/// <param name="entPath">DirectoryEntry的路径</param>
/// <returns>返回的是DirectoryEntry实例</returns>
ublic static DirectoryEntry GetDirectoryEntry(string entPath)
{
DirectoryEntry ent
if(UserName == null)
{
ent = new DirectoryEntry(entPath)
}
else
{
ent = new DirectoryEntry(entPath, HostName+"\\"+UserName, Password, AuthenticationTypes.Secure)
//ent = new DirectoryEntry(entPath, UserName, Password, AuthenticationTypes.Secure)
}
return ent
}
#endregio
#region 添加,删除网站的方法
ublic static void CreateNewWebSite(string hostIP, string portNum, string descOfWebSite, string commentOfWebSite, string webPath)
{
if(! EnsureNewSiteEnavaible(hostIP+portNum+descOfWebSite))
{
throw new ArgumentNullException("已经有了这样的网站了。" + Environment.NewLine + hostIP + portNum + descOfWebSite)
}
tring entPath = String.Format("IIS://{0}/w3svc", HostName)
DirectoryEntry rootEntry = GetDirectoryEntry(entPath);//取得iis路径
tring newSiteNum = GetNewWebSiteID(); //取得新网站ID
DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, "IIsWebServer"); //增加站点
ewSiteEntry.CommitChanges();//保存对区域的更改(这里对站点的更改)
ewSiteEntry.Properties["ServerBindings"].Value = hostIP + portNum + descOfWebSite
ewSiteEntry.Properties["ServerComment"].Value = commentOfWebSite
ewSiteEntry.CommitChanges()
DirectoryEntry vdEntry = newSiteEntry.Children.Add("root", "IIsWebVirtualDir")
vdEntry.CommitChanges()
vdEntry.Properties["Path"].Value = webPath
vdEntry.CommitChanges()
}
/// <summary>
/// 删除一个网站。根据网站名称删除。
/// </summary>
/// <param name="siteName">网站名称</param>
ublic static void DeleteWebSiteByName(string siteName)
{
tring siteNum = GetWebSiteNum(siteName)
tring siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum)
DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath)
tring rootPath = String.Format("IIS://{0}/w3svc", HostName)
DirectoryEntry rootEntry = GetDirectoryEntry(rootPath)
rootEntry.Children.Remove(siteEntry)
rootEntry.CommitChanges()
}
#endregio
#region Start和Stop网站的方法
ublic static void StartWebSite(string siteName)
{
tring siteNum = GetWebSiteNum(siteName)
tring siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum)
DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath)
iteEntry.Invoke("Start", new object[] {})
}
ublic static void StopWebSite(string siteName)
{
tring siteNum = GetWebSiteNum(siteName)
tring siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum)
DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath)
iteEntry.Invoke("Stop", new object[] {})
}
#endregio
#region 确认网站是否相同
/// <summary>
/// 确定一个新的网站与现有的网站没有相同的。
/// 这样防止将非法的数据存放到IIS里面去
/// </summary>
/// <param name="bindStr">网站邦定信息</param>
/// <returns>真为可以创建,假为不可以创建</returns>
ublic static bool EnsureNewSiteEnavaible(string bindStr)
{
tring entPath = String.Format("IIS://{0}/w3svc", HostName)
DirectoryEntry ent = GetDirectoryEntry(entPath)
foreach(DirectoryEntry child in ent.Children)
{
if(child.SchemaClassName == "IIsWebServer")
{
if(child.Properties["ServerBindings"].Value != null)
{
if(child.Properties["ServerBindings"].Value.ToString() == bindStr)
{
return false
}
}
}
}
return true
}
#endregio
#region 获取一个网站编号//一个输入参数为站点描述
/// <summary>
/// 输入参数为 站点的描述名 默认是站点描述为 "默认网站"
/// <exception cref="NotFoundWebSiteException">表示没有找到网站</exception>
ublic static string GetWebSiteNum(string siteName)
{
Regex regex = new Regex(siteName)
tring tmpStr
tring entPath = String.Format("IIS://{0}/w3svc", HostName)
DirectoryEntry ent = GetDirectoryEntry(entPath)
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)
}
#endregio
#region 获取新网站id的方法
/// <summary>
/// 获取网站系统里面可以使用的最小的ID。
/// 这是因为每个网站都需要有一个唯一的编号,而且这个编号越小越好。
/// 这里面的算法经过了测试是没有问题的。
/// </summary>
/// <returns>最小的id</returns>
ublic static string GetNewWebSiteID()
{
ArrayList list = new ArrayList()
tring tmpStr
tring entPath = String.Format("IIS://{0}/w3svc", HostName)
DirectoryEntry ent = GetDirectoryEntry(entPath)
foreach(DirectoryEntry child in ent.Children)
{
if(child.SchemaClassName == "IIsWebServer")
{
tmpStr = child.Name.ToString()
list.Add(Convert.ToInt32(tmpStr))
}
}
list.Sort()
int i = 1
foreach(int j in list)
{
if(i == j)
{
i++
}
}
return i.ToString()
}
#endregio
}
}