我是 C# 新手,我希望使用 C# 从 Active Directory 中提取数据并将其输出到 Excel 文件中。我看过一些教程,对如何做到这一点感到困惑。我正在寻找获取用户 ID、部门和名称。我将如何使用 .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"); *
*/
}
}
}
}
}