Search code examples
c#asp.netiisdirectoryservicesvirtual-directory

Checking whether a folder exists under an IIS application using C#


I'm working on a web based deployment tool in C# which deploys applications remotely on IIS 7.

I've reached a point where where I'm able to deploy an application. Now I need to see if the application that is deployed has a a certain directory before attempting to set permissions on it (Since the tool would deploy different applications which may or may not have that folder).

There are two approaches that I took:

  • I've checked for classes that I can use under the ServerManager namespace. I can get a handle on an application deployed under a certain application pool using:

    var iis = ServerManager.OpenRemote("serverName")

    var iisApplication = iis.Sites[site].Applications["appName"];.

    Now I can get the virtual directories under the application using :

    var virtualDirectory = iisApplication.VirtualDirectories;

    But then I'm not able to see a whole lot of folders which are under that virtual directory. For axample, my application is deployed as test and iisApplication.VirtualDirectories.First() gives me /test. I was want to be able to /test/_ApplicationLogs which is the directory I want to set permissions on.

  • My next approach was to use DirectoryEntry. Here, I'm not able to figure out the metabase path to use for my application. Is there a standard metabase path used for IIS 7?

    For an application called test deployed locally, what would the metabase path be? And would I be able to get all the children so that I can use DirectoryEntry.Exists?


Solution

  • For now, I have a workaround. I can use the WhatIf (set it true) property under DeploymentSyncOptions, do a sync and then check if an object got added. If it did, the directory does not exist. Code :

    var syncOptions = new DeploymentSyncOptions();
    syncOptions.WhatIf = true;
    
    using (deploymentObject)
    {
       var result = deploymentObject.SyncTo(
       DeploymentWellKnownProvider.SetAcl,
       "Default Web Site/path_to_folder",
       destinationBaseOptions,
       syncOptions);
    
       if (result.ObjectsAdded != 0)
       {
         syncOptions.WhatIf = false;
         deploymentObject.SyncTo(DeploymentWellKnownProvider.SetAcl,
                                "Default Web Site/path_to_folder",
                                 destinationBaseOptions,
                                 syncOptions);
       }
    }