You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForms展示AD用户最后登录时报specified cast is not valid错误如何解决

错误原因

你遇到的specified cast is not valid错误并不是最后转字符串的操作导致的,问题出在读取lastLogon属性的步骤:

  • 若目标用户从未登录过域,AD中不会生成lastLogon属性,此时直接访问de.Properties["lastLogon"][0]或者强转long都会触发转换失败
  • 部分场景下lastLogon属性值为空,直接强转也会报错
修复方案

增加属性非空判断,同时可以兼容从未登录的用户展示逻辑,同时也建议优化其他属性的读取逻辑,避免其他字段为空时也触发转换错误,修改后的代码如下:

lstActiveDirectory.Columns.Add("First Name", 150);
lstActiveDirectory.Columns.Add("Last Name", 150);
lstActiveDirectory.Columns.Add("Username", 150);
lstActiveDirectory.Columns.Add("Last Logon", 150);

DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
// 原代码里创建的DirectorySearcher未使用,可以直接删除
string[] arr = new string[4];
ListViewItem itm;

// 处理lastLogon属性
DateTime dtLastLogon;
if (de.Properties.Contains("lastLogon") && de.Properties["lastLogon"].Count > 0 && de.Properties["lastLogon"][0] != null)
{
    long lastLogon = (long)de.Properties["lastLogon"][0];
    dtLastLogon = DateTime.FromFileTime(lastLogon);
}
else
{
    dtLastLogon = DateTime.MinValue;
}

// 用Convert.ToString避免空值转换报错
arr[0] = Convert.ToString(de.Properties["givenName"].Value) ?? string.Empty;
arr[1] = Convert.ToString(de.Properties["sn"].Value) ?? string.Empty;
arr[2] = Convert.ToString(de.Properties["samAccountName"].Value) ?? string.Empty;
arr[3] = dtLastLogon == DateTime.MinValue ? "从未登录" : dtLastLogon.ToString("yyyy-MM-dd HH:mm:ss");

itm = new ListViewItem(arr);
lstActiveDirectory.Items.Add(itm);
补充说明

如果你的域环境存在多域控制器,还可以选择读取lastLogonTimestamp属性,这个属性会在域控之间同步,比单域控存储的lastLogon兼容性更好,读取逻辑和上面的lastLogon完全一致。

内容的提问来源于stack exchange,提问作者user14568805

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:21:00