December 01, 2003

Dump active directory to file in C#

// Purpose: To List all entries in Active Directory
// Author : Royans K Tharakan
// Date : 2003 Decusing System;
using System.DirectoryServices;
using System.Text.RegularExpressions;
namespace ActiveDirectorySearch1 {
class Class1 {
static void execute(String tab,String arg1, String args2) {
try{
DirectoryEntry entry = new DirectoryEntry("LDAP://YOURDOMAINNAME/"+arg1);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("("+args2+")");
mySearcher.SearchScope = SearchScope.OneLevel;
int i=0;
string reg1 = @"^CN=";
string reg3 = @"^OU=";
string reg2 = @args2;
Regex regex1=new Regex(reg1,RegexOptions.IgnoreCase);
Regex regex2=new Regex(reg2,RegexOptions.IgnoreCase);
Regex regex3=new Regex(reg3,RegexOptions.IgnoreCase);
foreach(SearchResult resEnt in mySearcher.FindAll()) {
i++;
Match m1=regex1.Match(resEnt.GetDirectoryEntry().Name.ToString());
Match m2=regex2.Match(resEnt.GetDirectoryEntry().Name.ToString());
Match m3=regex3.Match(resEnt.GetDirectoryEntry().Name.ToString());
String result=resEnt.GetDirectoryEntry().Name.ToString();
if (((m1.Success||(m3.Success) )&& (!m2.Success)))
{
Class1.execute("t"+tab,result+","+arg1,args2);
System.Collections.IEnumerator en = resEnt.Properties.PropertyNames.GetEnumerator();
while (en.MoveNext())
{
ResultPropertyValueCollection valcol = resEnt.Properties[en.Current.ToString()];
foreach(Object prop in valcol)
{
Console.WriteLine("t"+tab+en.Current.ToString()+"="+prop.ToString());
}
}
}
else
{
Console.WriteLine(tab+result);
}
Console.WriteLine(tab+result);
}
}
catch (Exception e)
{
Console.WriteLine("Error "+e);
}
}
static void Main(string[] args)
{
Class1.execute("t","DC=DOMAINNAME,DC=DOMAINNAME","ObjectClass=*");
}
}
}

No comments: