Archive for February 3, 2010
Getting Active Directory info for the current user in VB.net in 2 lines
8Don’t listen to the internet – getting account information from active directory for the current user is simple and easy in Visual Basic .NET – particularly if you are using Framework 3.5.
You don’t need to do any stinking LDAP queries, or lookups, or credential passings – it’s all made simple using System.DirectoryServices.AccountManagement. Observe.
First, go to the references tab in project properties, click add reference, and find “System.DirectoryServices.AccountManagement” – no need to add “System.DirectoryServices”.
Now, in your application, add the following lines:
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
(It’s even simpler if you import the namespace)
Poof. That’s it! You are done.
currentADUser is a strongly typed object containing attributes for most of the active directory properties you need = such as display name, email address, primary group membership, exchange mailbox info, etc, etc.
Say you want to get the current user’s email address. You could do it like so (after the previous code):
Dim userEmail as string = currentADUser.EmailAddress
That’s it. 1 additional line.
How about a concrete example – here is the problem I wanted to solve. Send an email message from the current user for error reporting – Make sure to change the To: email address, and the smtp server name, and this should be a drop-in solution:
Private Sub report_error(ByVal errorMessage As String)
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Dim mailClient As New System.Net.Mail.SmtpClient("smtpserver.company.local")
mailClient.Send(currentADUser.DisplayName & " <" & currentADUser.EmailAddress & ">", _
"notifications@company.com", _
"ERROR REPORT: Application error for " & currentADUser.DisplayName, _
errorMessage)
End Sub
Hope this helps!
