Skip to content

Instantly share code, notes, and snippets.

@berkayakcay
Last active July 20, 2016 08:24
Show Gist options
  • Save berkayakcay/6639962ed32132d934c73dcaf80308c5 to your computer and use it in GitHub Desktop.
Save berkayakcay/6639962ed32132d934c73dcaf80308c5 to your computer and use it in GitHub Desktop.
Active Directory CSV Export C#
string domainName = "YOUR_DOMAIN_NAME";
string cvspath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ActiveDirectoryList_" + Guid.NewGuid().ToString() + ".csv";
StringBuilder cvscontent = new StringBuilder();
cvscontent.AppendLine("SAMAccountName, givenName, sn, title, department, samAccountName, userPrincipalName");
using (var context = new PrincipalContext(ContextType.Domain, domainName))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
cvscontent.AppendLine(
string.Concat(
de.Properties["SAMAccountName"].Value, ", ",
de.Properties["givenName"].Value, ", ",
de.Properties["sn"].Value, ", ",
de.Properties["title"].Value, ", ",
de.Properties["department"].Value, ", ",
de.Properties["mail"].Value, ", ",
de.Properties["manager"].Value, ", ",
de.Properties["userPrincipalName"].Value
));
}
}
}
File.AppendAllText(cvspath, cvscontent.ToString(), Encoding.Unicode);
Console.WriteLine(cvscontent);
Console.ReadLine();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment