1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//src :
//https://stackoverflow.com/questions/5162897/how-can-i-get-a-list-of-users-from-active-directory
//https://stackoverflow.com/questions/10606334/using-principalsearcher-to-find-users-with-or-parameters
//https://stackoverflow.com/questions/1785751/how-to-get-company-and-department-from-active-directory-given-a-userprincipa
//add ref to :
//System.DirectoryServices
//System.DirectoryServices.AccountManagement
string line="";
using (StreamWriter outfile = new StreamWriter(Application.StartupPath + "\\export" + DateTime.Now.ToString("yyyyMMddHHmmss").ToString() + ".csv", true))
{
//streamwriter autoflush by default is true, on my test when reach the max memory, doing auto flush
//outfile.AutoFlush = true;
//otherwise you can use .Flush on every line
using (var context = new PrincipalContext(ContextType.Domain, "x.com"))
{
// query direct for a specific samaccount with :
// using (var searcher = new PrincipalSearcher(new UserPrincipal(context) { SamAccountName = "pipiscrew" }))
// else get all :
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
List<string> cols = new List<string> { "DisplayName", "samAccountName", "co", "EmployeeNumber", "Company", "WhenCreated", "whenchanged", "sAMAccountType", "LogonCount", "PrimaryGroupID", "msRTCSIP-UserEnabled" };
foreach (string col_item in cols)
{
line += "\"" + col_item + "\",";
}
outfile.WriteLine(line);
foreach (var result in searcher.FindAll())
{
line = "";
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
foreach (string col_item in cols)
{
if (de.Properties[col_item].Value == null)
{
line += ",";
continue;
}
line += "\"" + de.Properties[col_item].Value.ToString() + "\",";
}
outfile.WriteLine(line);
}
}
}
}
origin - http://www.pipiscrew.com/?p=10028 read-and-store-to-csv-all-users-from-active-directory