我正在尝试将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();
答案 0 :(得分:2)
您的问题在于帐户不必具有// ...
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()
属性。所以代码应该看起来像
{{1}}