使用c#在IIS中创建虚拟目录

时间:2009-08-07 08:30:24

标签: c# iis msbuild

这个需要一些解释......

我想自动设置IIS,因此我们的集成测试(使用Watin)可以在任何环境中运行。为此,我想创建一个将分别创建和销毁虚拟目录的Setup和Teardown。

我想到的解决方案是使用MSBuild Community Tasks在代码中使用模拟的IBuildEngine自动化IIS。

但是,当我尝试创建虚拟目录时,出现以下错误代码: 0x80005008 。 编辑:我删除了早期尝试中的工件,现在我得到 IndexOutOfRangeException

我在Vista上使用IIS7。 这是我用来运行任务的代码:

var buildEngine = new MockedBuildEngine();
buildEngine.OnError += (o, e) => Console.WriteLine("ERROR" + e.Message);
buildEngine.OnMessage += (o, e) => Console.WriteLine("MESSAGE" + e.Message);
buildEngine.OnWarning += (o, e) => Console.WriteLine("WARNING: " + e.Message);

var createWebsite = new MSBuild.Community.Tasks.IIS.WebDirectoryCreate()
                    {
                        ServerName = "localhost",
                        VirtualDirectoryPhysicalPath = websiteFolder.FullName,
                        VirtualDirectoryName = "MedicatiebeheerFittests",
                        AccessRead = true,
                        AuthAnonymous = true,
                        AnonymousPasswordSync = false,
                        AuthNtlm = true,
                        EnableDefaultDoc = true,
                        BuildEngine = buildEngine
                    };

createWebsite.Execute();

有人知道这里发生了什么吗?或者有人知道更好的方法吗?

3 个答案:

答案 0 :(得分:6)

这是我的应用程序使用的代码,它引用了System.DirectoryServices dll:

    using System.DirectoryServices;
    using System.IO;
    /// <summary>
    /// Creates the virtual directory.
    /// </summary>
    /// <param name="webSite">The web site.</param>
    /// <param name="appName">Name of the app.</param>
    /// <param name="path">The path.</param>
    /// <returns></returns>
    /// <exception cref="Exception"><c>Exception</c>.</exception>
    public static bool CreateVirtualDirectory(string webSite, string appName, string path)
    {
        var schema = new DirectoryEntry("IIS://" + webSite + "/Schema/AppIsolated");
        bool canCreate = !(schema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN");
        schema.Dispose();

        if (canCreate)
        {
            bool pathCreated = false;
            try
            {
                var admin = new DirectoryEntry("IIS://" + webSite + "/W3SVC/1/Root");

                //make sure folder exists
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    pathCreated = true;
                }

                //If the virtual directory already exists then delete it
                IEnumerable<DirectoryEntry> matchingEntries = admin.Children.Cast<DirectoryEntry>().Where(v => v.Name == appName);
                foreach (DirectoryEntry vd in matchingEntries)
                {
                    admin.Invoke("Delete", new[] { vd.SchemaClassName, appName }); 
                    admin.CommitChanges();
                    break;
                }

                //Create and setup new virtual directory
                DirectoryEntry vdir = admin.Children.Add(appName, "IIsWebVirtualDir");

                vdir.Properties["Path"][0] = path;
                vdir.Properties["AppFriendlyName"][0] = appName;
                vdir.Properties["EnableDirBrowsing"][0] = false;
                vdir.Properties["AccessRead"][0] = true;
                vdir.Properties["AccessExecute"][0] = true;
                vdir.Properties["AccessWrite"][0] = false;
                vdir.Properties["AccessScript"][0] = true;
                vdir.Properties["AuthNTLM"][0] = true;
                vdir.Properties["EnableDefaultDoc"][0] = true;
                vdir.Properties["DefaultDoc"][0] =
                    "default.aspx,default.asp,default.htm";
                vdir.Properties["AspEnableParentPaths"][0] = true;
                vdir.CommitChanges();

                //the following are acceptable params
                //INPROC = 0, OUTPROC = 1, POOLED = 2
                vdir.Invoke("AppCreate", 1);

                return true;
            }
            catch (Exception)
            {
                if (pathCreated)
                    Directory.Delete(path);
                throw;
            }
        }
        return false;
    }

答案 1 :(得分:1)

这可能有点延伸,因为它不是C#或MSBuild,但如何使用简单的vbscript来做呢?

http://msdn.microsoft.com/en-us/library/ms951564.aspx#autoadm_topic5

这可以在MSBuild任务中配置。

答案 2 :(得分:1)

如何使用Dylan建议的相同方法,但直接使用C#?

请参阅:Creating Sites and Virtual Directories Using System.DirectoryServices作为起点。