zoukankan      html  css  js  c++  java
  • C# 操作iis (安装包操作IIS以及属性介绍)

    安装包操作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      普通目录
    ..       文件


    //创建虚拟目录 
    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
    }
    }

  • 相关阅读:
    超详细的Chrome插件Vimium使用教程!
    Chrome浏览器快捷键详细介绍,让你摆脱鼠标的束缚!
    为什么你的电脑越来越卡?很可能是因为这个!
    像黑客一样用命令打开应用!
    电脑桌面乱?看完这篇文章是不存在这种情况的!
    任务栏简化,让你的任务栏更美观!
    USB无法识别?简单详细的驱动程序安装教程!
    文件扩展名是什么?有什么用?通俗易懂的文件扩展名讲解!
    Win2008 IIS7.5安装配置PHP7.3.2步骤,及500错误解决
    用命令行方式关闭CentOS防火墙
  • 原文地址:https://www.cnblogs.com/wujy/p/2333138.html
Copyright © 2011-2022 走看看