将lastlogontimestamp转换为DateTime

本文关键字:DateTime 转换 lastlogontimestamp | 更新日期: 2023-09-27 18:11:23

我正试图将lastlogontimestamp转换为datetime,但我注意到对于大值,我得到错误异常消息:索引超出范围。必须非负且小于集合的大小。

有没有更好的方法来做下面的事情?

var de = new DirectoryEntry("LDAP://GLOBAL.ABC.COM");
var ds = new DirectorySearcher(de);
ds.Filter = string.Format("(&(objectCategory=user)(objectClass=user)({0}={1}))", 
  "samAccountName", username);
ds.PropertiesToLoad.AddRange(new string[] { "samAccountName", "lastLogon" });
SearchResult sr = ds.FindOne();
long lastLogon = (long)sr.Properties["lastLogon"][0];
// lastLogon is 131111471723190497 
var dtLastLogon = DateTime.FromFileTime(lastLogon);
return dtLastLogon.ToString();

将lastlogontimestamp转换为DateTime

您的问题是帐户不必具有lastLogon属性。所以代码应该看起来像

// ...
SearchResult sr = ds.FindOne();
if (sr.Properties["lastLogon"] != null && sr.Properties["lastLogon"].Count > 0)
{
  long lastLogon = (long)sr.Properties["lastLogon"][0];
  var dtLastLogon = DateTime.FromFileTime(lastLogon);
  return dtLastLogon.ToString();
}
// last logon is not set here - make something up; for example
return DateTime.MinValue.ToString()