I am trying to execute the following code
using System.DirectoryServices; public bool HasVirtualDirectory(string serverName, string virtualDirectoryName) { try { DirectoryEntry directoryEntry = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/Root"); return directoryEntry.Children.Find(virtualDirectoryName, directoryEntry.SchemaClassName.ToString()) != null; } catch (Exception) { return false; } }
Since I need administrator privileges on the server to execute this code, I used this class to impersonate the correct user:
using (Impersonator impersonator = new Impersonator("username", "domain", "password")) { server.HasAccess = HasVirtualDirectory(server.HostName, virtualDirectory); }
But I still get a COMException: access is denied . On the other hand, if I do not use impersonation, but I run the program directly with the same credentials that I used in the impersonation (using "Run as user" in the context menu), it works as expected.
Running the program as an administrator (administrator on the computer on which the program is running, but not on the server) did not change anything, an exception still occurred.
I also tried ImpersonationLevel.SecurityDelegation (= 3) instead of ImpersonationLevel.SecurityImpersonation (= 2) in the DuplicateToken call, but this did not change anything (both the regular and the administrator executing the program).
To check the issued code, I tried the following code and it worked. (the user executing the program does not have the right to create a directory, but the user who impersonated himself).
using (Impersonator impersonator = new Impersonator("username", "domain", "password")) { Directory.CreateDirectory(@"\\servername\c$\tmp"); }
I am using Windows 7 Professional with activated UAC. The server is Windows Server 2003 R2 SP2.
Does anyone have any ideas?