AD Usre lastLogon Time

Problem with getting lastlogon for account - C#.NET / AD

Hi guys!
I have a code:

  1. StringLastlogon(string username,string domain)
  2. {
  3. try
  4. {
  5. {
  6. DirectoryContext context =newDirectoryContext(DirectoryContextType.Domain,domain);
  7. DateTime latestLogon =DateTime.MinValue;
  8. string servername =null;
  9. DomainControllerCollection dcc =DomainController.FindAll(context);
  10. foreach(DomainController dc in dcc)
  11. {
  12. DirectorySearcher ds;
  13. using(dc)
  14. using(ds = dc.GetDirectorySearcher())
  15. {
  16. ds.Filter=String.Format("(sAMAccountName={0})",username);
  17. ds.PropertiesToLoad.Add("lastLogon");
  18. ds.SizeLimit=1;
  19. SearchResult sr = ds.FindOne();
  20. if(sr !=null)
  21. {
  22. DateTimelastLogon=DateTime.MinValue;
  23. if(sr.Properties.Contains("lastLogon"))
  24. {
  25. lastLogon=DateTime.FromFileTime((long)sr.Properties["lastLogon"][0]);
  26. }
  27. if(DateTime.Compare(lastLogon, latestLogon)>0)
  28. {
  29. latestLogon =lastLogon;
  30. servername = dc.Name;
  31. }
  32. }
  33. }
  34. }
  35. return latestLogon.ToString();
  36. }
  37. }
  38. catch(Exception)
  39. {
  40. err =true;
  41. returnnull;
  42. }
  43. }
posted @ 2012-10-24 08:24  sirili  阅读(348)  评论(0编辑  收藏  举报