设为首页 收藏本站
查看: 1111|回复: 0

[经验分享] C# 操作iis (安装包操作IIS以及属性介绍)

[复制链接]

尚未签到

发表于 2015-8-15 09:39:53 | 显示全部楼层 |阅读模式
  安装包操作IIS的代码实例:
  
  #region
        private void CreateVirtualDir()
        {
            try
            {
                string constIISWebSiteRoot = "IIS://" + iis + "/W3SVC/1/ROOT";
                DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot);
                DirectoryEntry newRoot = root.Children.Add(port, root.SchemaClassName);
                newRoot.Properties["Path"][0] = dir;      //传来参数的目录地址
                newRoot.Properties["AppIsolated"][0] = 2;             // 值 0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池
                newRoot.Properties["AccessScript"][0] = true;          // 可执行脚本
                newRoot.Properties["AccessWrite"][0] = true;
                newRoot.Invoke("AppCreate", true);
                newRoot.Properties["DefaultDoc"][0] = "Default.aspx";//设置起始页
                newRoot.Properties["AppFriendlyName"][0] = port;   // 传来参数的应用程序名
                newRoot.CommitChanges();
                root.CommitChanges();
                string fileName = Environment.GetEnvironmentVariable("windir") + @"/Microsoft.NET/Framework/v4.0.30319/aspnet_regiis.exe";
                ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
                //处理目录路径
                string path = newRoot.Path.ToUpper();
                int index = path.IndexOf("W3SVC");
                path = path.Remove(0, index);
                //启动aspnet_iis.exe程序,刷新教本映射
                startInfo.Arguments = "-s " + path;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;
                Process process = new Process();
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
                string 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);
            }
        }
        #endregion
  
  
  .Net中需要使用ADSI来操作IIS
System.DirectoryServices命名空间--DirectoryEntry //在.net组件中 System.DirectoryServices.dll
了解IIS元数据(Metabase)的层次结构,每一个节点称之Key,而每个Key可以包含一或多个值,这些值就是我们说的属性(properties)
IIS元数据中的Key与IIS中的元素是相符的,因此元数据中的属性值的设定是会影响IIS中的设置。
Schema         指每个结点的类型
IIsVirtualDir  虚拟目录
IIsWebDir      普通目录
DSC0000.gif ..       文件

//创建虚拟目录
DirectoryEntry--目录入口。使用过ADSI的人都知道操作IIS时,需要提供他们的Path
这个Path的格式为: IIS://ComputerName/Service/Website/Directory

ComputerName   :即操作的服务器的名字,可以是名字也可以是IP,经常用的就是localhost
Service :即操作的服务器 如:
   W3SVC      Web
   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");
newVirDir.Invoke("AppCreate",true); //调用ADSI中的"AppCreate"方法将目录真正创建
newVirDir.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];
paras[0] = "IIsWebVirtualDir"; //表示操作的是虚拟目录
paras[1] = "Aspcn";
rootfolder.Invoke("Delete",paras);
rootfolder.CommitChanges();

asp.net(C#)操作IIS源代码,创建站点,管理虚拟目录等

using System;
using System.DirectoryServices;
using System.Collections;
using System.Text.RegularExpressions;
using System.Text;
namespace QF
{
public class IIS
{
#region UserName,Password,HostName的定义
public static string HostName
{
get
{
return hostName;
}
set
{
hostName = value;
}
}
public static string UserName
{
get
{
return userName;
}
set
{
userName = value;
}
}
public static string Password
{
get
{
return password;
}
set
{
if(UserName.Length <= 1)
{
throw new ArgumentException("还没有指定好用户名。请先指定用户名");
}
password = value;
}
}
public static void RemoteConfig(string hostName, string userName, string password)
{
HostName = hostName;
UserName = userName;
Password = password;
}
private static string hostName = "localhost";
private static string userName = "qf";
private static string password = "qinfei";
#endregion
#region 根据路径构造Entry的方法
/// <summary>
/// 根据是否有用户名来判断是否是远程服务器。
/// 然后再构造出不同的DirectoryEntry出来
/// </summary>
/// <param name="entPath">DirectoryEntry的路径</param>
/// <returns>返回的是DirectoryEntry实例</returns>
public 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;
}
#endregion
#region 添加,删除网站的方法
public 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);
}
string entPath = String.Format("IIS://{0}/w3svc", HostName);
DirectoryEntry rootEntry = GetDirectoryEntry(entPath);//取得iis路径
string newSiteNum = GetNewWebSiteID(); //取得新网站ID
DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, "IIsWebServer"); //增加站点
newSiteEntry.CommitChanges();//保存对区域的更改(这里对站点的更改)
newSiteEntry.Properties["ServerBindings"].Value = hostIP + portNum + descOfWebSite;
newSiteEntry.Properties["ServerComment"].Value = commentOfWebSite;
newSiteEntry.CommitChanges();
DirectoryEntry vdEntry = newSiteEntry.Children.Add("root", "IIsWebVirtualDir");
vdEntry.CommitChanges();
vdEntry.Properties["Path"].Value = webPath;
vdEntry.CommitChanges();
}
/// <summary>
/// 删除一个网站。根据网站名称删除。
/// </summary>
/// <param name="siteName">网站名称</param>
public static void DeleteWebSiteByName(string siteName)
{
string siteNum = GetWebSiteNum(siteName);
string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum);
DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
string rootPath = String.Format("IIS://{0}/w3svc", HostName);
DirectoryEntry rootEntry = GetDirectoryEntry(rootPath);
rootEntry.Children.Remove(siteEntry);
rootEntry.CommitChanges();
}
#endregion
#region Start和Stop网站的方法
public static void StartWebSite(string siteName)
{
string siteNum = GetWebSiteNum(siteName);
string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum);
DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
siteEntry.Invoke("Start", new object[] {});
}
public static void StopWebSite(string siteName)
{
string siteNum = GetWebSiteNum(siteName);
string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum);
DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
siteEntry.Invoke("Stop", new object[] {});
}
#endregion
#region 确认网站是否相同
/// <summary>
/// 确定一个新的网站与现有的网站没有相同的。
/// 这样防止将非法的数据存放到IIS里面去
/// </summary>
/// <param name="bindStr">网站邦定信息</param>
/// <returns>真为可以创建,假为不可以创建</returns>
public static bool EnsureNewSiteEnavaible(string bindStr)
{
string 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;
}
#endregion
#region 获取一个网站编号//一个输入参数为站点描述
/// <summary>
/// 输入参数为 站点的描述名 默认是站点描述为 "默认网站"
/// <exception cref="NotFoundWebSiteException">表示没有找到网站</exception>
public static string GetWebSiteNum(string siteName)
{
Regex regex = new Regex(siteName);
string tmpStr;
string 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);
}
#endregion
#region 获取新网站id的方法
/// <summary>
/// 获取网站系统里面可以使用的最小的ID。
/// 这是因为每个网站都需要有一个唯一的编号,而且这个编号越小越好。
/// 这里面的算法经过了测试是没有问题的。
/// </summary>
/// <returns>最小的id</returns>
public static string GetNewWebSiteID()
{
ArrayList list = new ArrayList();
string tmpStr;
string 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();
}
#endregion
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-99204-1-1.html 上篇帖子: iis rewrite 规则收集整理 下篇帖子: FW:介绍 IIS 7.5 的应用程序集区与新增的「虚拟账户」特性
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表