Creating virtual directories in sub directories in IIS 6.0 (programmatically)

1.1k views Asked by At

I am attempting to create virtual directories in IIS 6.0 programmatically and having problems checking if a virtual directory exists if the virtual directory is in a nested folder.

So if I have a folder tree such as:

MySite
  Folder A (virtual directory)
  Folder B
      NestedFolder C (virtual directory)

When I grab the DirectoryEntry object for this site metabase:

"IIS://<servername>/W3SVC/2/Root"

The DirectoryEntry object (will call it entry) will have two children, with

entry.Children[0].Name = "Folder A"

but entry.Children[1].Name = "Folder B" which is not a virtual directory. I have to do the following (code) to get to any virtual directories in nested folders:

foreach (var directoryEntry in entry.Children.Cast<DirectoryEntry>().Where(directoryEntry => directoryEntry.SchemaClassName == "IIsWebVirtualDir" || directoryEntry.SchemaClassName == "IIsWebDirectory")) {
            foreach (DirectoryEntry child in directoryEntry.Children.Cast<DirectoryEntry>().Where(subChild => subChild.SchemaClassName == "IIsWebVirtualDir")) {
                if (child.Name == vDir)
                    return true;
            }

            if (directoryEntry.Name != vDir) continue;
            return true;
        }

Which to me is quite ugly. Is there a better way that I can check for existing virtual directories if they exist in sub folders?

1

There are 1 answers

0
sisve On

Are you looking for a recursive function to iterate the complete site?

public static void Main() {
    var siteRoot = new DirectoryEntry("IIS://<servername>/W3SVC/2/Root");
    var containsVirtualDirectory = ContainsVirtualDirectory(siteRoot);
}

private static Boolean ContainsVirtualDirectory(DirectoryEntry container) {
    foreach (DirectoryEntry child in container.Children) {
        if (child.SchemaClassName == "IIsWebVirtualDir")
            return true;

        if (child.SchemaClassName == "IIsWebDirectory" && ContainsVirtualDirectory(child))
            return true;
    }

    return false;
}