iis6实现:

  1. DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
  2.         site.Invoke("Put", "ServerComment", webSiteName == "" ? ip : webSiteName);//网站名称,如果网站名称为空就用IP
  3.         //site.Invoke("Put", "ServerBindings", bd);//二级域名绑定
  4.         site.Invoke("Put", "ServerState", );//默认4
  5.         site.Invoke("Put", "DefaultDoc", "Default.aspx");
  6.         site.Invoke("Put", "ServerAutoStart", );//开启站点
  7.         site.Invoke("SetInfo");
  8.         DirectoryEntry siteVDir = site.Children.Add("ROOT", "IISWebVirtualDir");
  9.         siteVDir.Invoke("AppCreate", true); //创建应用程序站点
  10.         siteVDir.CommitChanges();
  11.         site.CommitChanges();
  12.         siteVDir.Properties["AppIsolated"][] = ;//默认2
  13.         siteVDir.Properties["Path"][] = pathToRoot;//主目录路径
  14.         siteVDir.Properties["AccessFlags"][] = ;
  15.         siteVDir.Properties["FrontPageWeb"][] = ;
  16.         siteVDir.Properties["AccessRead"][] = true; //设置读取权限
  17.         siteVDir.Properties["AccessWrite"][] = true;//写权限
  18.         siteVDir.Properties["AccessScript"][] = true;//执行权限
  19.         siteVDir.Properties["AppRoot"][] = "/LM/W3SVC/" + siteID + "/Root";
  20.         siteVDir.Properties["AppFriendlyName"][] = "默认应用程序";
  21.         siteVDir.Properties["AuthFlags"][] = ;//0表示不允许匿名访问,1表示就可以3为基本身份验证,7为windows继承身份验证
  22.         siteVDir.Properties["AspEnableParentPaths"][] = true;  //启用父路径
  23.         siteVDir.CommitChanges();
  24.         site.CommitChanges();

iis7以及以上版本实现:
详见这里:https://github.com/mohanak12/projectpilot/blob/a8f9d756b5b8fc19fbbf70e2484883215408540e/Flubu/Tasks/Iis/Iis7/Iis7CreateWebApplicationTask.cs

未测试

利用IIS7自带类库管理IIS现在变的更强大更方便,而完全可以不需要用DirecotryEntry这个类了(乐博网中很多.net管理iis6.0的文章都用到了DirecotryEntry这个类 ),Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\\System32\\InetSrv)下,使用时需要引用,它基本上可以管理IIS7的各项配置,这个类库的主体结构如下:

这里wenqi只举几个例子说明一下基本功能,更多功能请参考MSDN。

建立站点

string SiteName="乐博网"; //站点名称
string BindArgs="*:80:"; //绑定参数,注意格式
string apl="http"; //类型
string path="e:\\乐博网"; //网站路径
ServerManager sm = new ServerManager();
sm.Sites.Add(SiteName,apl,BindArgs,path);
sm.CommitChanges();

修改站点

Site site=sm.Sites["newsite"];
site.Name=SiteName;
site.Bindings[0].EndPoint.Port=9999;
site.Applications[0].VirtualDirectories[0].PhysicalPath=path;
sm.CommitChanges();

删除站点

Site site=sm.Sites["乐博网"];
sm.Sites.Remove(site);
sm.CommitChanges();

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

#region CreateWebsite 添加网站

public string CreateWebSite(string serverID, string serverComment, string defaultVrootPath, string HostName, string IP, string Port)

{

try

{

ManagementObject oW3SVC = new ManagementObject (_scope, new ManagementPath(@"IIsWebService='W3SVC'"), null);

if (IsWebSiteExists (serverID))

{

return "Site Already Exists...";

}

ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters ("CreateNewSite");

ManagementBaseObject[] serverBinding = new ManagementBaseObject[1];

serverBinding[0] = CreateServerBinding(HostName, IP, Port);

inputParameters["ServerComment"] = serverComment;

inputParameters["ServerBindings"] = serverBinding;

inputParameters["PathOfRootVirtualDir"] = defaultVrootPath;

inputParameters["ServerId"] = serverID;

ManagementBaseObject outParameter = null;

outParameter = oW3SVC.InvokeMethod("CreateNewSite", inputParameters, null);

// 启动网站

string serverName = "W3SVC/" + serverID;

ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);

webSite.InvokeMethod("Start", null);

return (string)outParameter.Properties["ReturnValue"].Value;

}

catch (Exception ex)

{

return ex.Message;

}

}

public ManagementObject CreateServerBinding(string HostName, string IP, string Port)

{

try

{

ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath("ServerBinding"), null);

ManagementObject serverBinding = classBinding.CreateInstance();

serverBinding.Properties["Hostname"].Value = HostName;

serverBinding.Properties["IP"].Value = IP;

serverBinding.Properties["Port"].Value = Port;

serverBinding.Put();

return serverBinding;

}

catch

{

return null;

}

}

#endregion

页面:

// 添加网站

protected void AddWebsite_Click(object sender, EventArgs e)

{

IISManager iis = new IISManager();

iis.Connect();

string serverID = "5556";

string serverComment = "Create Website";

string defaultVrootPath = @"D:\web";

string HostName = "World";

string IP = "";

string Port = "9898";

ReturnMessage.Text = iis.CreateWebSite(serverID,serverComment,defaultVrootPath,HostName,IP,Port);

}

删除网站的代码:

#region DeleteSite 删除站点

public string DeleteSite(string serverID)

{

try

{

string serverName = "W3SVC/" + serverID;

ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);

webSite.InvokeMethod("Stop", null);

webSite.Delete();

webSite = null;

return "Delete the site succesfully!";

}

catch(Exception deleteEx)

{

return deleteEx.Message;

}

}

#endregion

同样的方式,也可以对网站对属性进行修改。

附:IIS的站点属性(详细内容,请查阅IIS帮助)

Read only properties of W3SVC/1/Root:             // 只读属性

AppIsolated = 2             属性指出应用程序是在进程内、进程外还是在进程池中运行。值 0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池。

AppPackageID =           为事务提供 COM+ 应用程序标识符 (ID)。此 ID 在由组件服务管理的所有事务中使用。

AppPackageName =      为事务提供 COM+ 应用程序名。

AppRoot = /LM/W3SVC/1/ROOT 包含到应用程序根目录的配置数据库路径。

Caption =              提供对象的一段简短文本描述(一行字符串)。

Description =         提供对象的一段较长文本描述。

InstallDate =          表示安装对象的时间。缺少值并不表示对象没有安装。

Name = W3SVC/1/ROOT     定义了用来识别对象的标签。创建子类时,可以将 Name 属性改写为 Key 属性。

Status =         表示对象当前状态。各种可操作的和不可操作的状态都可以被定义。可操作的状态为“正常”、“已降级”和“预见故障”。“预见故障”表示一个组件可能运行正常但预计很快会出现故障。例如,启用 SMART 的硬盘。还可指定不可操作的状态。这些状态为“错误”、“启动”、“停止”和“服务”。后者(即“服务”)可用于磁盘镜像过程、重新加载用户权限列表其他管理作业。并不是所有这类作业都联机;所以,被管理的组件不是“正常”状态处于任何其他状态。

Read/Write properties of W3SVC/1/Root:            // 可读/可写

AccessExecute = False  值 true 表示不论文件类型是什么,文件文件夹的内容都可以执行。

AccessFlags = 513 包含有用于配置文件访问权限的标志

AccessNoPhysicalDir = False

AccessNoRemoteExecute = False 值 true 表示拒绝远程请求执行应用程序;如果将 AccessExecute 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteExecute 设置为 false 来启用远程请求,将 AccessExecute 设置为 false 来禁止本地请求。

AccessNoRemoteRead = False      值 true 表示拒绝远程请求查看文件;如果将 AccessRead 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteRead 设置为 false 来启用远程请求,将 AccessRead 设置为 false 来禁止本地请求。

AccessNoRemoteScript = False    值 true 表示拒绝远程请求查看动态内容;如果将 AccessScript 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteScript 设置为 false 来启用远程请求,将 AccessScript 设置为 false 来禁止本地请求。

AccessNoRemoteWrite = False     值 true 表示拒绝远程请求创建更改文件;如果将 AccessWrite 属性设置为 true,只有来自 IIS 服务器所在的相同计算机的请求才会成功。您不能将 AccessNoRemoteWrite 设置为 false 来启用远程请求,将 AccessWrite 设置为 false 来禁止本地请求。

AccessRead = True              值 true 表示可通过 Microsoft Internet Explorer 读取文件文件夹的内容。

AccessScript = True             值 true 表示如果是脚本文件静态内容,则可以执行文件文件夹的内容。值 false 只允许提供静态文件,如 HTML 文件。

AccessSource = False           值 true 表示如果设置了读取写入权限,则允许用户访问源代码。源代码包括 Microsoft? Active Server Pages (ASP) 应用程序中的脚本。

AccessSSL = False        值 true 表示文件访问需要带有不带有客户端证书的 SSL 文件权限处理。

AccessSSL128 = False         值 true 表示文件访问需要至少 128 位密钥、带有不带有客户端证书的 SSL 文件权限处理。

AccessSSLFlags = 0             默认值 0 表示未设置任何 SSL 权限。

AccessSSLMapCert = False  值 true 表示 SSL 文件权限处理将客户端证书映射到 Microsoft Windows? 操作系统的用户帐户上。要实现映射,必须将 AccessSSLNegotiateCert 属性设置成 true。

AccessSSLNegotiateCert = False  值 true 表示 SSL 文件访问处理从客户端请求证书。值 false 表示如果客户端没有证书,仍可继续访问。如果服务器请求证书但证书不可用(即使也将 AccessSSLRequireCert 设成 true),某些版本的 Internet Explorer 将关闭连接。

AccessSSLRequireCert = False     值 true 表示 SSL 文件访问处理从客户端请求证书。如果客户端没有提供证书,连接会关闭。当使用 AccessSSLRequireCert 时,必须将 AccessSSLNegotiateCert 设成 true。

AccessWrite = False             值 true 表示允许用户将文件及其相关属性上载到服务器上已启用的目录中,者更改可写文件的内容。只有使用支持 HTTP 1.1 协议标准的 PUT 功能的浏览器,才能执行写入操作。

AdminACLBin =                   由 Microsoft? Exchange Server 使用

AnonymousPasswordSync = True       指出 IIS 是否应该为试图访问资源的匿名用户处理用户密码。下表列出了该属性行为的详细说明:如果将 AnonymousPasswordSync 设置为 false,管理员必须手动设置匿名用户密码的 AnonymousUserPass 属性;否则匿名访问将无法正常工作。 如果将 AnonymousPasswordSync 设置为 true,将由 IIS 设置匿名用户密码。 如果将 AnonymousPasswordSync 设置为 true 并且配置数据库属性 AllowAnonymous 值为 false,则不允许任何用户登录到 FTP 服务器。

AnonymousUserName = IUSR_COMPUTERNAME    指定用来验证匿名用户的已注册的本地用户名。服务器将每个服务器操作与用户名和密码关联起来。

AnonymousUserPass = XXXXXXXXXXXX      指定用来验证匿名用户的已注册的本地用户密码。服务器将每个服务器操作与用户名和密码关联起来。

AppAllowClientDebug = False       指定是否允许客户端调试。该属性与应用于服务器端调试的 AppAllowDebugging 无关。

AppAllowDebugging = False  指定是否允许在服务器上进行 ASP 调试。该属性与应用于客户端调试的 AppAllowClientDebug 属性无关。

AppFriendlyName = 默认应用程序     软件包应用程序的用户好记名称

AppOopRecoverLimit = -1           进程外应用程序在出现故障后重新启动的最大次数。服务器不会响应超出该范围的组件请求。该属性不适用于进程内运行的应用程序扩展。

AppPoolId = ASP.NET V2.0  应用程序在其中路由的应用程序池

AppWamClsid =                   为应用程序的 Web 应用程序管理 (WAM) 接口提供类 ID

AspAllowOutOfProcComponents = True     在 IIS 4.0 中,AspAllowOutOfProcComponents 属性指定是否允许 ASP 脚本调用进程外组件,这些组件是在应用程序内启动的可执行程序。在 IIS 5.0 中,该属性已过时,并且属性值将被忽略。但是,使用该属性的脚本仍然可以正常运行。

AspAllowSessionState = True       启用 ASP 应用程序会话状态持续性。如果将该值设置为 true,那么服务器将为每个连接创建 Session 对象,可访问会话状态,允许会话存储,出现 Session_OnStart 和 Session_OnEnd 事件,并且发送 ASPSessionID Cookie 到客户端。如果将该值设置为 false,那么不允许状态访问和存储,事件将不进行处理,并且也不发送 Cookie。

AspAppServiceFlags = 0              包含在 IIS 应用程序上启用 COM+ 服务所必须要设置的标志

AspBufferingLimit = 4194304       设置 ASP 缓冲区的最大大小。如果启动了响应缓冲,该属性将控制在进行刷新前 ASP 页面可以向响应缓冲区写入的最大字节数

AspBufferingOn = True        ASP 应用程序的输出是否需要缓冲

AspCalcLineNumber = True  ASP 是否计算和存储已执行代码的行号,以便在错误报告中提供

AspCodepage = 0                 为应用程序指定默认的代码页

AspDiskTemplateCacheDirectory = %windir%\system32\inetsrv\ASP Comp     目录的名称,该目录是 ASP 在存储器内的缓存溢出后,用来将已编译的 ASP 模板存储到磁盘的目录

AspEnableApplicationRestart = True     确定 ASP 应用程序能否自动重新启动

AspEnableAspHtmlFallback = False      当由于请求队列已满而拒绝新的请求时,AspEnableAspHtmlFallback 属性控制 ASP 的行为。将该属性设置为 true,将导致发送与请求的 .asp 文件名称类似的 .htm 文件(如果存在),而不是发送 .asp 文件。.htm 文件的命名约定是 .asp 文件名之后附加一个 _asp。例如,.asp 文件是 hello.asp,那么 .htm 文件应该是 hello_asp.htm。

AspEnableChunkedEncoding = True            指定是否为万维网发布服务(WWW 服务)启动 HTTP 1.1 chunked 传输编码

AspEnableParentPaths = False             页面是否允许当前目录的相对路径(使用 ..\ 表示法)。

AspEnableSxs = False                  值 true 将启动 COM+ 并排集合,该程序集允许 ASP 应用程序指定要使用哪个版本的系统 DLL 传统 COM 组件,例如 MDAC、MFS、MSVCRT、MSXML 等等。

AspEnableTracker = False            值 true 将启动 COM+ 跟踪器,管理员开发人员可用其来调试 ASP 应用程序。

AspEnableTypelibCache = True            是否在服务器上缓存类型库

AspErrorsToNTLog = False         是否将 IIS 脚本错误写入到 Windows 事件日志中

AspExceptionCatchEnable = True        页面是否捕获组件产生的异常。如果设置为 false (者禁用),那么 Microsoft 脚本调试程序工具将不捕捉所调试的组件发生的异常。

AspExecuteInMTA = 0                 ASP 能够在一个多线程单元 (MTA) 中运行其全部线程。如果 COM 组件主要是自由线程双线程组件,则将 ASP 线程作为 MTA 运行可显著改善性能。默认情况下,AspExecuteInMTA 属性设置为 0,这意味着 ASP 不在 MTA 中执行。在应用程序级别上将该属性设置为 1 可以使 ASP 在 MTA 中运行。

AspKeepSessionIDSecure = 0              启用 AspKeepSessionIDSecure 属性后,它可以确保将 SessionID 作为安全 Cookie 发送(如果已在安全通道上分配的话)。

AspLCID = 2048                         用程序指定默认的区域设置标识符 (LCID)。

AspLogErrorRequests = True              控制 Web 服务器是否将失败的客户请求写入到 Windows 事件日志文件中

AspMaxDiskTemplateCacheFiles = 2000      指定存储已编译 ASP 模板的最大数量。存储已编译模板的目录由 AspDiskTemplateCacheDirectory 属性配置。

AspMaxRequestEntityAllowed = 204800      指定一个 ASP 请求的实体正文中允许的最多字节数。

AspPartitionID =                  COM+ 分区用于将 Web 应用程序隔离到其各自的 COM+ 分区。COM+ 分区保存不同的自定义 COM 组件的版本。将 AspPartitionID 属性设置为 COM+ 分区的全局唯一标识符 (GUID)。同时,设置 AspAppServiceFlags 配置数据库属性的 AspUsePartition 标志。在应用程序级别设置这两个属性

AspProcessorThreadMax = 25             指定 IIS 可创建的每个处理器的最大工作线程数

AspQueueConnectionTestTime = 3              IIS 将所有的 ASP 请求放置到队列中。如果请求在队列中等待的时间比 AspQueueConnectionTestTime 属性指定的时间(以秒为单位)长,则 ASP 将在执行请求前检查确定客户端是否仍是连接的。如果客户端已断开连接,则不处理该请求并且从队列中删除该请求。

AspQueueTimeout = -1                允许 ASP 脚本请求在队列中等待的时间(以秒为单位)。无穷大表示为 -1。

AspRequestQueueMax = 3000             允许进入队列的并发 ASP 请求的最大数目。在队列占满时,任何试图请求 ASP 文件的客户端浏览器都将收到 HTTP 500“服务器太忙”的错误。

AspRunOnEndAnonymously = True            指定了 SessionOnEnd 和 ApplicationOnEnd 全局 ASP 函数是否应该作为匿名用户运行

AspScriptEngineCacheMax = 250        页面将在内存中保持缓存的脚本引擎的最大数目

AspScriptErrorMessage = 处理 URL 时服务器出错。请与系统管理员联系。    特殊调试错误没有被发送到客户端时(如果将 AspScriptErrorSentToBrowser 设置成 false)将发送给浏览器的错误消息

AspScriptErrorSentToBrowser = True  Web 服务器是否将调试细节(文件名、错误、行号、描述)写到客户端浏览器,并且记录到 Windows 事件日志中

AspScriptFileCacheSize = 500             要缓存的预编译脚本文件数。如果设置为 0,则不缓存任何脚本文件

AspScriptLanguage = VBScript            运行在 Web 服务器上的所有 ASP 应用程序的默认脚本语言

AspScriptTimeout = 90                AspScriptTimeout 属性指定了在终止脚本和将事件写入 Windows 事件日志之前,ASP 页面允许的脚本运行时间的默认值(以秒为单位)。

AspSessionMax = -1                    IIS 允许的最大并发会话数。当达到该限制时,如果客户端试图与 IIS 建立新连接,则客户端将接收到错误信息(HTTP 500“服务器太忙”)。无穷大表示为 -1。

AspSessionTimeout = 20                     完成最后的与 Session 对象相关的请求后,保留该对象的时间(以分钟为单位)。

AspSxsName =             启动并行 (SxS) 程序集。并行 (SxS) 程序集允许 ASP 应用程序指定要使用哪个版本的系统 DLL 传统 COM 组件,例如 MDAC、MFS、MSVCRT、MSXML 等。

AspTrackThreadingModel = False        IIS 是否检查应用程序创建的任意组件的线程模块。

AspUsePartition = False        值 true 将启动 COM+ 分区,可用其将 Web 应用程序隔离到各自的 COM+ 分区。COM+ 分区可拥有不同的自定义 COM 组件的版本。如果设置该标志,请同时设置 AspPartitionID 配置数据库属性。

AuthAdvNotifyDisable = True              禁用密码到期预先通知

AuthAnonymous = True               指定匿名身份验证作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。

AuthBasic = False                 指定基本身份验证作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。

AuthChangeDisable = True           禁止更改密码

AuthChangeUnsecure = False              允许在不安全端口更改密码

AuthChangeURL = /iisadmpwd/achg.asp      用户输入新密码时被调用的 URL

AuthExpiredUnsecureURL = /iisadmpwd/aexp3.asp     用户密码到期时调用的 URL

AuthExpiredURL = /iisadmpwd/aexp.asp      用户密码到期时调用的 URL。将以安全的 (HTTPS) 方式调用它。

AuthFlags = 5                      作为有效方案返回给客户端的 Windows 验证方案的设置

AuthMD5 = False                        指定摘要式身份验证和高级摘要式身份验证作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。

AuthNotifyPwdExpUnsecureURL = /iisadmpwd/anot3.asp  包含一个特定的 URL:如果用户的密码在 PasswordExpirePreNotifyDays 中指定的天数前到期,则调用该 URL。

AuthNotifyPwdExpURL = /iisadmpwd/anot.asp   包含一个特定的 URL:如果用户的密码在 PasswordExpirePreNotifyDays 中指定的天数前到期,则调用该 URL。将以安全的 (HTTPS) 方式调用它。

AuthNTLM = True                      指定集成 Windows 身份验证(也称作质询/响应 NTLM 验证)作为可能的 Windows 验证方案之一,返回给客户端作为有效验证方案。

AuthPassport = False                   true 的值表示启用了 Microsoft? .NET Passport 身份验证

AuthPersistence = 64                   指定了使用 NTLM 验证跨越连接上的请求时的验证持久性

AuthPersistSingleRequest = True         将该标志设置成 true 指定验证仅对一个连接上的单个请求持久。IIS 在每个请求的末尾重设验证,并且在会话的下一个请求上强制执行重验证。

AzEnable = False                  用于虚拟目录、应用程序,配置数据库中项相应的 URL 的 URL 授权。

AzImpersonationLevel = 0            用于应用程序的模拟行为,该模拟行为允许配置 Web 应用程序模拟客户端用户、IIS 工作进程,工作进程的 IUSER_* 帐户。

AzScopeName =                         将虚拟目录、应用程序 URL 与作用域相关联。如果没有指定作用域指定了空子符串,则使用 IIS 6.0 URL 授权的默认作用域。

AzStoreName =                           授权管理器策略存储与虚拟目录、应用程序 URL 相关联。

CacheControlCustom =                指定了自定义 HTTP 1.1 缓存控制指令

CacheControlMaxAge = 0                   指定了 HTTP 1.1 缓存控制最大时间值。

CacheControlNoCache = False             保护缓存内容的 HTTP 1.1 指令

CacheISAPI = True                     在第一次使用 ISAPI 扩展后是否在内存中进行缓存。

Caption =                            提供对象的一段简短文本描述(一行字符串)。

CGITimeout = 300               指定 CGI 应用程序超时(以秒为单位)。

ContentIndexed = True                指定安装的目录索引程序是否应该检索该目录树下的内容。

CreateCGIWithNewConsole = False            指示 CGI 应用程序是否在自己的控制台上运行。

CreateProcessAsUser = True        是在系统环境中创建 CGI 进程还是在请求用户环境中创建 CGI 进程。

DefaultDoc = index.aspx,default.aspx   包含一个多个默认文档的文件名,如果在客户端的请求中不包含文件名,将把默认文档的文件名返回给客户端。

DefaultDocFooter =                     附加到返回到客户端的 HTML 文件的自定义页脚(页脚并不附加到 ASP 文件)。

DefaultLogonDomain =                服务器用来对用户进行身份验证的默认域(在 UserIsolationMode = 2 的 Web 宿主方案中)。

Description =                       提供对象的一段较长文本描述。

DirBrowseFlags = 1073741886            可以提供多少目录和文件信息(如果启用浏览)以及目录中是否包含默认页的标记。

DirBrowseShowDate = True        设置为 true 时,浏览目录时将显示日期信息。

DirBrowseShowExtension = True        设置为 true 时,浏览目录时将显示文件扩展名。

DirBrowseShowLongDate = True        设置为 true 时,显示目录时将在扩展格式中显示日期信息。

DirBrowseShowSize = True         设置为 true 时,浏览目录时将显示文件大小信息。

DirBrowseShowTime = True        设置为 true 时,显示目录时将显示文件时间信息。

DisableStaticFileCache = False             目录的静态文件缓存

DoDynamicCompression = False         与 HcDoDynamicCompression 属性相同。

DontLog = False                         是否将客户端的请求写入日志文件。

DoStaticCompression = False              与 HcDoStaticCompression 属性相同。

EnableDefaultDoc = True                    设置为 true 时,浏览目录时系统会加载该目录的默认文档(由 De, faultDoc 属性指定)。

EnableDirBrowsing = False           设置为 true 时,将启用目录浏览。

EnableDocFooter = False                    启用禁用由 DefaultDocFooter 属性指定的自定义页脚。

EnableReverseDns = False            启用禁用万维网发布服务(WWW 服务)的反向域名服务器 (DNS) 查找。

FrontPageWeb = True                  服务器实例是否由 Microsoft? FrontPage? 处理。

方法二:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.DirectoryServices;
  5. namespace WindowsApplication1
  6. {
  7. class IISManager
  8. {
  9. public IISManager()
  10. {
  11. }
  12. public static string VirDirSchemaName = "IIsWebVirtualDir";
  13. private string _serverName;
  14. public string ServerName
  15. {
  16. get
  17. {
  18. return _serverName;
  19. }
  20. set
  21. {
  22. _serverName = value;
  23. }
  24. }
  25.  
  26. /// <summary>
  27. /// 创建網站或虚拟目录
  28. /// </summary>
  29. /// <param name="WebSite">服务器站点名称(localhost)</param>
  30. /// <param name="VDirName">虚拟目录名称</param>
  31. /// <param name="Path">實際路徑</param>
  32. /// <param name="RootDir">true=網站;false=虛擬目錄</param>
  33. /// <param name="iAuth">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows驗證...更多請查閱MSDN</param>
  34. /// <param name="webSiteNum">1</param>
  35. /// <param name="serverName">一般為localhost</param>
  36. /// <returns></returns>
  37. public bool CreateWebSite(string WebSite, string VDirName, string Path, bool RootDir, int iAuth, int webSiteNum, string serverName)
  38. {
  39. try
  40. {
  41. System.DirectoryServices.DirectoryEntry IISSchema;
  42. System.DirectoryServices.DirectoryEntry IISAdmin;
  43. System.DirectoryServices.DirectoryEntry VDir;
  44. bool IISUnderNT;
  45.  
  46. //
  47. // 确定IIS版本
  48. //
  49. IISSchema = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/Schema/AppIsolated");
  50. if (IISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN")
  51. IISUnderNT = true;
  52. else
  53. IISUnderNT = false;
  54. IISSchema.Dispose();
  55. //
  56. // Get the admin object
  57. // 获得管理权限
  58. //
  59. IISAdmin = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/W3SVC/" + webSiteNum + "/Root");
  60. //
  61. // If we're not creating a root directory
  62. // 如果我们不能创建一个根目录
  63. //
  64. if (!RootDir)
  65. {
  66. //
  67. // If the virtual directory already exists then delete it
  68. // 如果虚拟目录已经存在则删除
  69. //
  70. foreach (System.DirectoryServices.DirectoryEntry v in IISAdmin.Children)
  71. {
  72. if (v.Name == VDirName)
  73. {
  74. // Delete the specified virtual directory if it already exists
  75. try
  76. {
  77. IISAdmin.Invoke("Delete", new string[] { v.SchemaClassName, VDirName });
  78. IISAdmin.CommitChanges();
  79. }
  80. catch (Exception ex)
  81. {
  82. throw ex;
  83. }
  84. }
  85. }
  86. }
  87. //
  88. // Create the virtual directory
  89. // 创建一个虚拟目录
  90. //
  91. if (!RootDir)
  92. {
  93. VDir = IISAdmin.Children.Add(VDirName, "IIsWebVirtualDir");
  94. }
  95. else
  96. {
  97. VDir = IISAdmin;
  98. }
  99. //
  100. // Make it a web application
  101. // 创建一个web应用
  102. //
  103. if (IISUnderNT)
  104. {
  105. VDir.Invoke("AppCreate", false);
  106. }
  107. else
  108. {
  109. VDir.Invoke("AppCreate", true);
  110. }
  111. //
  112. // Setup the VDir
  113. // 安装虚拟目录
  114. //AppFriendlyName,propertyName,, bool chkRead,bool chkWrite, bool chkExecute, bool chkScript,, true, false, false, true
  115. VDir.Properties["AppFriendlyName"][0] = VDirName; //应用程序名称
  116. VDir.Properties["AccessRead"][0] = true; //设置读取权限
  117. VDir.Properties["AccessExecute"][0] = false;
  118. VDir.Properties["AccessWrite"][0] = false;
  119. VDir.Properties["AccessScript"][0] = true; //执行权限[純腳本]
  120. //VDir.Properties["AuthNTLM"][0] = chkAuth;
  121. VDir.Properties["EnableDefaultDoc"][0] = true;
  122. VDir.Properties["EnableDirBrowsing"][0] = false;
  123. VDir.Properties["DefaultDoc"][0] = "Default.aspx,Index.aspx,Index.asp"; //设置默认文档,多值情况下中间用逗号分割
  124. VDir.Properties["Path"][0] = Path;
  125. VDir.Properties["AuthFlags"][0] = iAuth;
  126. //
  127. // NT doesn't support this property
  128. // NT格式不支持这特性
  129. //
  130. if (!IISUnderNT)
  131. {
  132. VDir.Properties["AspEnableParentPaths"][0] = true;
  133. }
  134. //
  135. // Set the changes
  136. // 设置改变
  137. //
  138. VDir.CommitChanges();
  139.  
  140. return true;
  141. }
  142. catch (Exception ex)
  143. {
  144. throw ex;
  145. }
  146. }
  147. /// <summary>
  148. /// 獲取VDir支持的所有屬性
  149. /// </summary>
  150. /// <returns></returns>
  151. public string GetVDirPropertyName()
  152. {
  153. //System.DirectoryServices.DirectoryEntry VDir;
  154. const String constIISWebSiteRoot = "IIS://localhost/W3SVC/1/ROOT/iKaoo";
  155. DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot);
  156. string sOut = "";
  157. //下面的方法是得到所有属性名称的方法:
  158. foreach (PropertyValueCollection pvc in root.Properties)
  159. {
  160. //Console.WriteLine(pvc.PropertyName);
  161. sOut += pvc.PropertyName + ":" + pvc.Value.ToString() + "-----------";
  162. }
  163. return sOut;
  164. }
  165. /// <summary>
  166. /// 創建虛擬目錄
  167. /// </summary>
  168. /// <param name="sDirName">虛擬目錄程式名稱</param>
  169. /// <param name="sPath">實體路徑</param>
  170. /// <param name="sDefaultDoc">黙認首頁,多個名稱用逗號分隔</param>
  171. /// <param name="iAuthFlags">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows驗證...更多請查閱MSDN</param>
  172. /// <param name="sWebSiteNumber">Win2K,2K3支持多個網站,本次操作哪個網站,黙認網站為1</param>
  173. /// <returns></returns>
  174. public bool CreateVDir(string sDirName, string sPath, string sDefaultDoc, int iAuthFlags, string sWebSiteNumber)
  175. {
  176. try
  177. {
  178. String sIISWebSiteRoot = "IIS://localhost/W3SVC/" + sWebSiteNumber + "/ROOT";
  179. DirectoryEntry root = new DirectoryEntry(sIISWebSiteRoot);
  180. foreach (System.DirectoryServices.DirectoryEntry v in root.Children)
  181. {
  182. if (v.Name == sDirName)
  183. {
  184. // Delete the specified virtual directory if it already exists
  185. root.Invoke("Delete", new string[] { v.SchemaClassName, sDirName });
  186. root.CommitChanges();
  187. }
  188. }
  189. DirectoryEntry tbEntry = root.Children.Add(sDirName, root.SchemaClassName);
  190.  
  191. tbEntry.Properties["Path"][0] = sPath;
  192. tbEntry.Invoke("AppCreate", true);
  193. //tbEntry.Properties["AccessRead"][0] = true;
  194. //tbEntry.Properties["ContentIndexed"][0] = true;
  195. tbEntry.Properties["DefaultDoc"][0] = sDefaultDoc;
  196. tbEntry.Properties["AppFriendlyName"][0] = sDirName;
  197. //tbEntry.Properties["AccessScript"][0] = true;
  198. //tbEntry.Properties["DontLog"][0] = true;
  199. //tbEntry.Properties["AuthFlags"][0] = 0;
  200. tbEntry.Properties["AuthFlags"][0] = iAuthFlags;
  201. tbEntry.CommitChanges();
  202. return true;
  203. }
  204. catch (Exception ex)
  205. {
  206. throw ex;
  207. }
  208. }
  209.  
  210. }
  211.  
  212. }
  213. 调用DEMO
  214. private void button1_Click(object sender, EventArgs e)
  215. {
  216. if (new IISManager().CreateWebSite("localhost", "Vtest", "E:\\DOC", false, 1, 1, "localhost"))
  217. lbInfo.Text = "Create Vtest OK";
  218. }
  219. private void button2_Click(object sender, EventArgs e)
  220. {
  221. txtPN.Text = new IISManager().GetVDirPropertyName();
  222. }
  223. private void button3_Click(object sender, EventArgs e)
  224. {
  225. if (new IISManager().CreateVDir("iKaoo", "E:\\DOC", "index.aspx,Default.aspx", 1, "1"))
  226. lbInfo.Text = "Create iKaoo OK";
  227. }

C#操作 iis启用父目录的更多相关文章

  1. iis 启用父目录路径访问

    今天公司有个客户保修网站后台无法访问,我查看了源代码,发现ASP代码本身并没有什么问题.而且我下到本地能够访问.就是在网上不能正常连接,显示入下错误: Server.MapPath() 错误 'ASP ...

  2. 用C#操作IIS创建虚拟目录和网站

    #region CreateWebsite 添加网站 public string CreateWebSite(string serverID, string serverComment, string ...

  3. 无法加载父级样式或设置IIS的asp站点启用父路径

    打开IIS 1.单击站点,在"IIS"区域中找到ASP图标,双击. 2.找到"启用父路径"项目,将对应的值设置为"TRUE"即可.   顶

  4. Win7/Win2008下IIS配置Asp网站启用父路径的设置方法(已解决)

    Win7/Win2008下IIS配置Asp网站启用父路径的设置方法(已解决) 在Win7/Win2008下IIS配置Asp网站启用父路径的设置方法与win2003下不同,看看下图就知道了.

  5. C# 使用代码来操作 IIS

    由于需要维护网站的时候,可以自动将所有的站点HTTP重定向到指定的静态页面上. 要操作 IIS 主要使用到的是“Microsoft.Web.Administration.dll”. 该类库不可以在引用 ...

  6. IIS启用GZip压缩

    IIS启用GZip压缩,是提高网站速度和减轻服务器负载的一个优化手段和方法,经测试,网站启用GZip压缩后,速度快了3倍!而配置起来也相当的简单,因此被广大网站管理员使用.本文将详细介绍如何在IIS启 ...

  7. asp启用父路径

    开启父路径后可以用../来表示上一层目录,如果网站程序中使用了../,不开启则网站程序里有../就会报错. IIS6启用父路径方法:打开IIS管理器——网站——右键属性——主目录——配置——选项——选 ...

  8. IIS启用GZip压缩的详细教程(图文)

    本文将详细介绍如何在IIS启用GZip压缩,同时解决可能遇到的一些问题 IIS启用GZip压缩,是提高网站速度和减轻服务器负载的一个优化手段和方法,经测试,网站启用GZip压缩后,速度快了3倍!而配置 ...

  9. 恢复 Windows 7 的“回到父目录”按钮

    Windows 7 使用以来很多方面一直不习惯,特别是让我无比纠结的”回到父目录“ 按钮从资源管理器中消失了. 不能不说这是一个失败! 很多时候,Win 7 地址栏中自以为是的显示的很多层目录层次的面 ...

随机推荐

  1. 在Github上搭建博客

    貌似还是这个链接最靠谱呀 http://my.oschina.net/nark/blog/116299   如何利用github建立个人博客:之一 在线编辑器http://markable.in/ed ...

  2. Easy install ryu

    参考:Ubuntu14.04安装Ryu控制器 环境:Ubuntu 14.04 64bit 使用pip安装ryu: // dependencies sudo apt-get install Python ...

  3. Python学习札记(三十四) 面向对象编程 Object Oriented Program 5

    参考:获取对象信息 NOTE 1.type()函数可以用来判断对象的类型: >>> type(123) <class 'int'> >>> type(' ...

  4. gif&png&jpg&webp

    几种图片格式的区别和联系 1.http://www.tuicool.com/articles/AbUvI3A

  5. Kolakoski数列

    2018-04-16 15:40:16 Kolakoski序列是一个仅由1和2组成的无限数列,是一种通过“自描述”来定义的数列.他在整数数列大全网站上排名第二位,足见该数列在组合数学界中的重要性. K ...

  6. Spring 及 SpringMVC的web.xml配置详解

    出处http://blog.csdn.net/u010796790 1.spring 框架解决字符串编码问题:过滤器 CharacterEncodingFilter(filter-name) 2.在w ...

  7. K-Means算法的收敛性和如何快速收敛超大的KMeans?

    不多说,直接上干货! 面试很容易被问的:K-Means算法的收敛性. 在网上查阅了很多资料,并没有看到很清晰的解释,所以希望可以从K-Means与EM算法的关系,以及EM算法本身的收敛性证明中找到蛛丝 ...

  8. ssh隧道(通过跳板机)连接mysql

    案例: A服务器   B服务器   C服务器mysql 现在mysql服务器C只能通过内网访问,B服务器就能通过内网连接访问到mysql A服务器无法直接连接C服务器mysql,所以要通过跳板机(跳板 ...

  9. IOS-工程师Mac上的必备软件

      前言   iOS工程师一直都是那么的高逼格,用的是Mac电脑,耍的是iPhone手机,哇咔咔~~  但是,作为一名iOS开发工程师,我们除了高逼格外,还必须是全能的.你不会点UI设计.不会点后台语 ...

  10. GVIM设置背景颜色

    首先找到GVim的安装目录,在安装目录下你可以发现一个_vimrc文件,使用文本编辑器打开后在里面添加两行代码即可:代码如下set gfn=Courier_New:h14colorscheme tor ...