开发者

.NET and Active Directory - System.Exception: General access denied error

开发者 https://www.devze.com 2023-02-21 18:11 出处:网络
I keep getting this error when I try to create a new user. This is the part of my code that give me the error:

I keep getting this error when I try to create a new user.

This is the part of my code that give me the error:

Public Function CreateAdAccount(ByVal sUserName As String, ByVal sPassword As String, ByVal sFirstName As String,开发者_StackOverflow社区 ByVal sLastName As String, ByVal sGroupName As String) As Boolean
   Dim bResult As Boolean = True
   Dim dirEntry As New DirectoryEntry(ADFullPath)

   SetCultureAndIdentity()

   ' 1. Create user account
   Dim adUsers As DirectoryEntries
   Dim newUser As DirectoryEntry

   If Not UserExists(sUserName) Then
      Try
         adUsers = dirEntry.Children
         newUser = adUsers.Add("CN=" & sUserName, "user")

         ' 2. Set properties
         SetProperty(newUser, "givenname", sFirstName)
         SetProperty(newUser, "sn", sLastName)
         SetProperty(newUser, "SAMAccountName", sUserName)
         SetProperty(newUser, "userPrincipalName", sUserName)
         SetProperty(newUser, "displayName", sFirstName & " " & sLastName)

         Try
            newUser.CommitChanges()
         Catch ex As Exception
            Err.Raise(4938, "clsSource", ex.Message)
         End Try

The error happens on this line: newUser.CommitChanges()

i can't seem to figure out why it keeps breaking. i tried to login as the admin in to AD and create a new user. it worked fine...


If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

Basically, you can define a domain context and easily create new users:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// create a new user
UserPrincipal newUser = new UserPrincipal(ctx);

// define properties
newUser.GivenName = sFirstName;
newUser.Surname = sLastName;
newUser.SamAccountName = sUserName;
newUser.UserPrincipalName = sUserName;
newUser.DisplayName = sFirstName + " " + sLastName;

// save changes
newUser.Save();

I'm not sure what you have in sUserName - but the .UserPrincipalName property should always be something like someuser@somedomain.com - does your user name contain such a value? If not - maybe try to use that kind of a notation for your user principal name.

The new S.DS.AM makes it really easy to play around with users and groups in AD:

0

精彩评论

暂无评论...
验证码 换一张
取 消