我是C#的新手,我希望使用C#从Active Directory中提取数据并将其输出到excel文件中。我看了几个教程,并对如何做到这一点感到困惑。我想获取userID,Department和Name。我如何使用.FindAll()功能?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace ADquery
{
class UserLookUp
{
static void Main(string[] args)
{
Console.WriteLine(retrieveUsers());
Console.ReadLine();
}
public static string retrieveUsers()
{
string path = ("LDAP://OU=IS,OU=People,DC=Corporate,DC=Amfam,DC=com");
//Init instance of DirectoryEntry
DirectoryEntry dEntry = new DirectoryEntry(path);
DirectorySearcher dSearcher = new DirectorySearcher(dEntry);
//Establish filter (all users)?
dSearcher.Filter = "(&(objectCategory=person)(objectClass=user)(cn=*))";
foreach (SearchResult searchResults in dSearcher.FindAll())
{
if (searchResults.Properties["CN"][0].ToString() != null)
{
//pull info desired
ResultPropertyValueCollection valueCollection =
searchResults.Properties["manager"];
foreach (Object propertyValue in valueCollection)
{
Console.WriteLine("Property Value: " + (string)propertyValue.ToString());
}
Console.WriteLine(" ");
catch ( InvalidOperationException iOe )
{
dSearcher.Dispose();
}
catch ( NotSupportedException nSe )
{
}
finally
{
if(sResults != null)
sResults.Dispose();
}
/*
// Create new Excel file.
var excelFile = new ExcelFile();
// Foreach DataTable, add new worksheet and insert data from DataTable into it.
foreach (DataTable dataTable in dataSet.Tables)
excelFile.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, 0, 0, true);
// Save Excel file to XLS format.
excelFile.SaveXls(dataSet.DataSetName + ".xls"); *
*/
}
}
}
}
}
答案 0 :(得分:1)
必须是这样的:
public void WriteEntries(DirectoryEntry domainRoot)
{
DirectorySearcher searcher = new DirectorySearcher(domainRoot);
searcher.PropertiesToLoad.Add("displayName");
searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("department");
searcher.Filter = "(&(objectCategory=person))";
foreach (SearchResult result in searcher.FindAll())
{
// Login Name
Console.WriteLine(GetProperty(result, "cn"));
// Display Name
Console.WriteLine(GetProperty(result, "displayName"));
// Department
Console.WriteLine(GetProperty(result, "department"));
}
}
private string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
使用带有根条目的WriteEntries
进行搜索。我在控制台中编写它们,您可以将它们放在excel行中。要使用Excel,我建议您使用exellibrary。