最近在CSDN论坛里看见网友的一片偏关于使用.net 创建虚拟目录的帖子, 以前一直以为不能用托管代码实现这个功能... 在此总结一下:) 下面是创建虚拟目录的代码 const String constIISWebSiteRoot = "IIS://localhost/W3SVC/1/ROOT"; string virtualDirName = "virtualName";//虚拟目录名称 string physicalPath = @"c:\1"; DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot); DirectoryEntry tbEntry = root.Children.Add(virtualDirName, root.SchemaClassName); tbEntry.Properties["Path"][0] = physicalPath; tbEntry.Invoke("AppCreate", true); tbEntry.Properties["AccessRead"][0] = false; tbEntry.Properties["ContentIndexed"][0] = true; ; tbEntry.Properties["DefaultDoc"][0] = "index.asp,Default.aspx"; tbEntry.Properties["AppFriendlyName"][0] = virtualDirName; tbEntry.Properties["AccessScript"][0] = true; tbEntry.Properties["DontLog"][0] = true; tbEntry.Properties["AuthFlags"][0] = 0; tbEntry.Properties["AuthFlags"][0] = 1; tbEntry.CommitChanges(); 现在来解释一下这段代码: 创建虚拟目录需要使用System.DirectoryEntries命名空间下的DirectoryEntry类 首先声明一个DirecotryEntry的实例 DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot); 其中的参数constIISWebSiteRoot由一下几个部分组成 "IIS://"+domainName+"/W3SVC"+WebSiteNumber+"/ROOT" WebSiteNumber由你要在哪个站点创建虚拟目录来决定,xp只能有一个站点,所以WebSiteNumber值为1,win2000Server 和win2003可以创建多个站点,所以WebSiteNumber的值可以大于1 然后创建DirecotryEntry实例的子节点 ,也就是要创建的虚拟目录 DirectoryEntry tbEntry = root.Children.Add(virtualDirName, root.SchemaClassName); root.Children.Add(string namespace,string schemaClassName)方法会创建并返回一个DirectoryEntry的实例 下面的部分就是对这个新创建的节点进行操作了 tbEntry.Properties["Path"][0] = physicalPath; //设置虚拟目录指向的物理路径 tbEntry.Invoke("AppCreate", true); // tbEntry.Properties["AccessRead"][0] = false; //设置读取权限 tbEntry.Properties["DefaultDoc"][0] = "index.asp,Default.aspx"; //设置默认文档,多值情况下中间用逗号分割 tbEntry.Properties["AppFriendlyName"][0] = virtualDirName; //应用程序名称 tbEntry.Properties["AccessScript"][0] = true; //执行权限 tbEntry.Properties["AuthFlags"][0] = 0; // 设置目录的安全性,0表示不允许匿名访问,1为允许,3为基本身份验证,7为windows继承身份验证 tbEntry.CommitChanges();// 这里这是列举了部分属性,如果得到更多属性的信息可是访问DirecotryEntry.Properties属性下面的方法是得到所有属性名称的方法:foreach (PropertyValueCollection pvc in tbEntry.Properties) { Console.WriteLine(pvc.PropertyName); }演示代码CreateVirtualSite.rar

评论