Thursday 1 May 2014

How to get data from Active Directory using C#

1. Include the System.DirectoryServices library in u r .Net Application.
DirectoryEntry entry = new DirectoryEntry(LDAPServer);
entry.AuthenticationType = AuthenticationTypes.Secure;
entry.Username = LDAPUserName;
entry.Password = LDAPPassWord;
DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
string GroupString = string.Empty;
string strGroupName = null;
mySearcher.Filter = "SAMAccountName=" + strUserName;
mySearcher.PropertiesToLoad.Add("memberOf");
int propertyCount;
try
{
SearchResult objSearchResult = mySearcher.FindOne();
propertyCount = objSearchResult.Properties["memberOf"].Count;
string dn = null;
int equalsIndex;
int commaIndex;
for (int i = 0; i <= propertyCount - 1; i++)
{
dn = objSearchResult.Properties["memberOf"][i].ToString();
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (equalsIndex == -1)
{
return null;
}
if (dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).Equals(ReadWrite))
{
//User belongs to readwrite group
strGroupName = ReadWrite;
break;
}
else if (dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).Equals(ReadOnly))
{
//User belongs to onlyread group
strGroupName = ReadOnly;
break;
}
else
{
//User belongs to non of onlyread and readwrite group
strGroupName = null;
}
}
return strGroupName;
}
catch
{ throw; }