(EDIT) The plot thickens: The same code (without the need for impersonation!) Is successfully executed with the Windows 7 client, but NOT with the Windows 2008 R2 client! Here is the code in question. (The original message follows the code below.)
var entry = new DirectoryEntry("IIS://" + tbHost.Text + "/W3SVC", tbUsername.Text, tbPassword.Password); foreach (DirectoryEntry site in entry.Children) { Console.Write("Site {0}\n", site.Name); foreach (PropertyValueCollection prop in site.Properties) Console.Write("{0}={1}\n", prop.PropertyName, prop.Value); }
I read here that for the IIS provider, you cannot pass credentials when creating the DirectoryEntry object. You have to do impersonation . So I tried the following code, but I still get a COMException with the text "Unknown error (0x80005000)" when I try to read the property, as in the case when I tried to pass the username and password to the DirectoryEntry constructor earlier. Here is a summary:
LogonUser() successful, credentials are in order. I hit my head a bit before I discovered that I needed to use LOGON32_LOGON_NEW_CREDENTIALS instead of LOGON32_LOGON_INTERACTIVE .- The remote computer is not in the same domain. In fact, this is not at all in the domain. In fact, I put its name in the
hosts client hosts so that I can get it by name. - Running Metabase Explorer on the target machine shows that the key I want to read exists. (See the picture at the end of the message.)
.
const int LOGON32_LOGON_INTERACTIVE = 2; const int LOGON32_LOGON_NETWORK = 3; const int LOGON32_LOGON_NEW_CREDENTIALS = 9; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_PROVIDER_WINNT50 = 3; const int LOGON32_PROVIDER_WINNT40 = 2; const int LOGON32_PROVIDER_WINNT35 = 1; [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern int LogonUser(String lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll")] extern static int GetLastError(); (...) IntPtr myToken = IntPtr.Zero; if (LogonUser(tbUsername.Text, tbHost.Text, tbPassword.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref myToken) == 0) { int causingError = GetLastError(); throw new System.ComponentModel.Win32Exception(causingError); } WindowsImpersonationContext myMission = WindowsIdentity.Impersonate(myToken); string mbUri = "IIS://" + tbHost.Text + "/MimeMap"; DirectoryEntry myDirEntry = new DirectoryEntry(mbUri); Console.Write("{0}\n", myDirEntry.Properties["KeyType"]); myDirEntry.Close(); myMission.Undo(); if (myToken != IntPtr.Zero) CloseHandle(myToken);

Jccyc source share