Note: This code assumes you have a DirectoryEntry pointing to the Configuration-Naming Context
1 /// <summary>
2 /// Searches the forrest for the directory entry of the given user.
3 /// </summary>
4 /// <param name="principalname">Name of the user to find. Must be in the form domain</param>
5 /// <param name="useGC">Specifies whether to use the Global Catalog to find the user. If false, a standard LDAP-Query is used.</param>
6 /// <returns>The directoryentry of the user, if it is found. Null otherwise.</returns>
7 public DirectoryEntry FindUser(string principalname, bool useGC)
8 {
9 DirectoryEntry searchRoot;
10 DirectorySearcher searcher;
11 string[] name;
12 string ncName;
13
14 name = principalname.Split('\\\\');
15 if (name.Length != 2) throw new ArgumentException("principalname is not in the correct format", principalname);
16
17 ncName = ResolveNetBiosNameToDN(name[0]);
18
19 searchRoot = GetDirectoryEntry(ncName, useGC);
20
21 searcher = new DirectorySearcher(searchRoot,
22 string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))", name[1]),
23 new string[] {"distinguishedName"}, SearchScope.Subtree);
24
25 try
26 {
27 return searcher.FindOne().GetDirectoryEntry();
28 }
29 catch (NullReferenceException ex)
30 {
31 throw new ArgumentException("The given username was not found", "principalname", ex);
32 }
33 }
34
35 private string ResolveNetBiosNameToDN(string netbiosName)
36 {
37 try
38 {
39 return (string) GetDirectoryEntry(string.Format("CN={0}, CN=Partitions, {1}", netbiosName, (string) ConfigurationNamingContext.Properties["distinguishedName"].Value)).Properties["nCName"].Value;
40 }
41 catch (System.Runtime.InteropServices.COMException ex)
42 {
43 if ((uint) ex.ErrorCode == 0x80072030) throw new ArgumentException("The given netbios name was invalid", "netbiosName", ex);
44 else throw;
45 }
46 }
47
48 public DirectoryEntry GetDirectoryEntry(string distinguishedName)
49 {
50 return GetDirectoryEntry(distinguishedName, false);
51 }
52
53 public DirectoryEntry GetDirectoryEntry(string distinguishedName, bool useGC)
54 {
55 string path;
56
57 path = (useGC) ? "GC://" : "LDAP://";
58 if (_Server != null) path += _Server;
59
60 if ((!path.EndsWith("/")) && (distinguishedName != "")) path += "/";
61 path += distinguishedName;
62
63 if (path.EndsWith("//")) path = path.Remove(path.Length-2, 2);
64
65 return new DirectoryEntry(path, Username, Password, _AuthenticationType);
66 }