Search code examples
c#iis-6directoryservices

How to Use System.DirectoryServices to Access a Web Server on a Different Domain


I am trying to write a simple program to list the virtual directories of an IIS server, which is on a different domain than my local machine. When creating the root DirectoryEntry object, I tried to pass in the credentials with a domain qualifier, like this:

DirectoryEntry entry = new DirectoryEntry("IIS://myremoteserver/W3SVC/1/Root", "mydomain\\myusername", "mypassword");

I get an "Access is Denied" exception, however. Is this the right way to do this? All the code examples I've found only access the local web server. I running WinXP SP3 locally, and trying to connect to a Win2003 R2 (64-bit) server running IIS version 6.0.


Solution

  • I decided to use the System.Management classes to do this instead, which works when I use a domain qualifier in the login:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Management;
    
    namespace MyProgram
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                ConnectionOptions options = new ConnectionOptions();
                options.Authentication = AuthenticationLevel.PacketPrivacy;
                options.Username = "somedomain\\username";
                options.Password = "password";
                ManagementPath path = new ManagementPath();
                path.Server = "someserver";
                path.NamespacePath = "root/MicrosoftIISv2";
                ManagementScope scope = new ManagementScope(path, options);
    
                string Query = "select * from IIsWebVirtualDirSetting";
                using (ManagementObjectSearcher search = new ManagementObjectSearcher(scope, new ObjectQuery(Query)))
                {
                    ManagementObjectCollection results = search.Get();
                    foreach (ManagementObject obj in results)
                    {
                        Console.WriteLine(obj.Properties["Name"].Value);
                    }                
                }          
                Console.ReadLine();
            }
        }
    }