DirectoryEntry.NativeObject throws access denied f

2019-02-15 18:15发布

问题:

I have a local user, which is member of Administrators local group.

When I run this code:

using System;
using System.DirectoryServices;

namespace nanttest
{
    class Program
    {
        public static void Main(string[] args)
        {
            using(DirectoryEntry entry = new DirectoryEntry("IIS://localhost/W3SVC"))
            {
                object absobject = entry.NativeObject;
                Console.WriteLine("Name: {0}", entry.Name);
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

I receive:

Unhandled Exception: System.Runtime.InteropServices.COMException (0x80070005): Access is denied.

at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_NativeObject() at nanttest.Program.Main(String[] args) in c:\Work\nanttest\nanttest\Program.cs:line 20

If I run this code while logged in as Administrator, it works OK.

Also, this code fails if I run it logged in as a DomainAdmin user. I have added MYDOMAIN\DomainAdmins and MYDOMAIN\mydomainuser as members of local Administrators group.

What other permissions should I add for these users, so they can run this code.

回答1:

To answer my own question, so others can find a solution:

The problem is with the default UAC settings in Windows 2008. Even if a user is in the Administrators group, he/she still needs elevated privileges to run some operations (the one above appears to be among them).

So, solution 1 - run the application using "Run as administrator", or start it from a command prompt, which was started with that option.

Solution 2: Disable UAC for administrators group - I have used method #3 from this article (group policy changes). Remember to reboot the server after these changes.