Thursday, March 13, 2008

C# code talking to Active Directory

For one of my clients work the requirment is like that we have users fill out Infopath forms 2007. So there needs to be a code behind (c#) to validate the user in the domain to find from which group he is from.... doing that it came my mind how will i get all the email Ids from a domain... Yup following is the code the talks to your Active Directory in the domain & gets all the Email IDs available....
Belive me, i am not a spammer.... i just do these things for fun :)

using System.DirectoryServices;

namespace ConsoleApplication1
{
class Program
{
static void Main (string[] args)
{
SAM d = new SAM();
string f = d.GetEmail("*");

}

}

class SAM
{
public string GetEmail(string ntname)
{

DirectorySearcher objsearch = new DirectorySearcher();

string strrootdse = objsearch.SearchRoot.Path;

DirectoryEntry objdirentry = new DirectoryEntry(strrootdse);

objsearch.Filter = "(& (mailnickname=" + ntname.Trim() + ")(objectClass=user))";

objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;

objsearch.PropertiesToLoad.Add("mail");

objsearch.PropertyNamesOnly = true;

SearchResultCollection colresults = objsearch.FindAll();

string arl = "";

foreach (SearchResult objresult in colresults)
{

arl = arl + objresult.GetDirectoryEntry().Properties["mail"].Value + ";";

}

if (arl.Length > 0)

arl = arl.Substring(0, arl.Length - 1);

objsearch.Dispose();

return arl;
}
}

}

No comments: