我用一下代码获取所有的AD账号,但是提示“指定的域不存在,或无法联系。
”:
DirectorySearcher mySearcher = new DirectorySearcher();//想搜索出所有,此处可省参数
mySearcher.Filter = ("(objectClass=user)"); //user表示用户,group表示组
mySearcher.PageSize = 10000;//查询的个数,默认是1000,设置大一点就可以找到域中所有的账号
foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
{
DirectoryEntry user = resEnt.GetDirectoryEntry();
string _ou = user.Parent.Name.Split('=')[1];//获取组织
if (_ou != "Computers")//排除所有的计算机账号
{
DataRow dr = dt.NewRow();
dr["sAMAccountName"] = string.Empty;
dr["Name"] = string.Empty;
dr["mail"] = string.Empty;
dr["OU"] = string.Empty;
if (user.Properties.Contains("sAMAccountName"))
{
dr["sAMAccountName"] = user.Properties["sAMAccountName"][0].ToString();
}
if (user.Properties.Contains("Name"))
{
dr["Name"] = user.Properties["Name"][0].ToString();
}
if (user.Properties.Contains("mail"))
{
dr["mail"] = user.Properties["mail"][0].ToString();
}
if (user.Parent.Name != string.Empty && user.Parent.Name.IndexOf('=') > -1)
{
//获取用户所在的组织单位
dr["OU"] = user.Parent.Name.Split('=')[1];
}
dt.Rows.Add(dr);
}
}