Skip to content

Instantly share code, notes, and snippets.

@painquin
Created March 7, 2012 13:51
Show Gist options
  • Save painquin/1993271 to your computer and use it in GitHub Desktop.
Save painquin/1993271 to your computer and use it in GitHub Desktop.
LDAP helper (works in MVC)
using System.DirectoryServices;
public class LDAP
{
static DirectoryEntry _de = new DirectoryEntry("LDAP://[LDAP server host]", "[service account]", "[service account password]");
static T LookupAnd<T>(string LoginName, System.Func<SearchResult,T> cb)
{
using (var dsearch = new DirectorySearcher(_de))
{
dsearch.Filter = "(&(objectClass=person)(SAMAccountName=" + LoginName.Split('\\')[1] + "))";
var user = dsearch.FindOne();
if (user == null)
{
return default(T);
}
return cb(user);
}
}
public static string GetUsername(string LoginName)
{
return LookupAnd(LoginName, u => u.Properties["Name"][0].ToString());
}
public static string GetEmail(string LoginName)
{
return LookupAnd(LoginName, u => u.Properties["mail"][0].ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment