本文介绍了模拟无法为DirectoryServices工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下代码

I'm 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;
    }
}

由于我需要服务器上的管理员权限才能执行此代码,因此我使用了此类以模拟正确的用户:

As I need adminstrator rights 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);
}

但是我仍然收到 COMException:访问被拒绝.另一方面,如果我不使用模拟,但我使用模拟中使用的相同凭据直接运行程序(通过在上下文菜单中使用以其他用户身份运行"),则程序将按预期运行.

But I still get the COMException: Access is denied. On the other hand, if I don't use the impersonate but I run the program directly with the same credentials I used in the impersonate (by using "Run as different user" in the context menu) it works as expected.

以管理员身份运行程序(运行程序的计算机上的管理员,而不是服务器上的管理员)没有进行任何更改,仍然发生了异常.

Running the program as administrator (administrator on the machine running the program, but not administrator on the server) did not change anything, the exception still occured.

我还在DuplicateToken调用中尝试了ImpersonationLevel.SecurityDelegation(= 3)而不是ImpersonationLevel.SecurityImpersonation(= 2),但这并没有改变任何东西(无论是普通用户还是执行程序的管理员用户).

I also tried ImpersonationLevel.SecurityDelegation (=3) instead of ImpersonationLevel.SecurityImpersonation (=2) in the DuplicateToken call, but that did not change anything either (both as normal or administrator user executing the program).

为了测试模拟代码,我尝试了以下代码,并且可以正常工作. (执行该程序的用户无权创建目录,而模拟用户则具有创建目录的权限.)

To test the impersonate code, I tried the following code, and that worked. (the user executing the program does not have the rights to create the directory, but the impersonated user does).

using (Impersonator impersonator = new Impersonator("username", "domain", "password"))
{
    Directory.CreateDirectory(@"\\servername\c$\tmp");
}

我正在使用Windows 7 Professional(已激活UAC).该服务器是Windows Server 2003 R2 SP2.

I'm using Windows 7 Professional with UAC activated. The server is a Windows Server 2003 R2 SP2.

有人有什么想法吗?

推荐答案

使用 DirectoryEntry构造函数(字符串,字符串,字符串,AuthenticationTypes),它使用用户名和密码代替模拟.

Use the DirectoryEntry Constructor (String, String, String, AuthenticationTypes) that takes a username and password instead of impersonation.

DirectoryEntry directoryEntry = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/Root", @"domain\username", "password", AuthenticationTypes.Secure | AuthenticationTypes.Sealing);

这篇关于模拟无法为DirectoryServices工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 20:24