Ok, so I've made my connection to the AD server, and created users without any issues. However, when I try to get a list of users, it always fails.
I can connect using LDAP://domain.com, "user", "password" but when I try anything else, the access violation comes up. EX: LDAP://CN=Users,DC=domain,DC=com or LDAP://domain.com/CN=Users,DC=domain,DC=com returns the access violation exception. If I do a search through the root and get the path, and create a new entry with the path, I get the access violation.
It seems like I can only connect to the root. I don't know how to get a list of users from there. Can anyone help?
EDIT: This is the code I ended up working with. It works the way I want it to. I'll leave it up here in case anyone ever runs into this problem. I've added comments to the code where the error popped up.
private void List_Logon()
{
DirectoryEntry Entry = new DirectoryEntry("LDAP://domain.com", "user", "password", AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(Entry);
searcher.Filter = "(&(objectCategory=person)(objectClass=user))";
SearchResultCollection results = searcher.FindAll();
//I had to add null checks. This was never a problem, but should be checked.
if (results != null)
{
//For some odd reason, I couldn't use a foreach here.
for (int i = 0; i < results.Count; i++)
{
try
{
DirectoryEntry user = results[i].GetDirectoryEntry();
//This information cannot return null or it will throw an Access Violation Exception.
if (user.Properties["Name"].Value != null & user.Properties["lastLogon"].Value != null)
{
//This part is not mine. Someone else told me how to convert it.
Int64 lastlogon = new Int64();
IADsLargeInteger lgInt =
(IADsLargeInteger)user.Properties["lastLogon"].Value;
lastlogon = ((long)lgInt.HighPart << 32) + lgInt.LowPart;
DateTime lastLogonTime = DateTime.FromFileTime(lastlogon);
//Thank you.
listBox1.Items.Add(user.Properties["Name"].Value.ToString() + " : " + lastLogonTime.ToString());
}
//If one of the above is null, I still want to try to get the user.
else if (user.Properties["Name"].Value != null)
{
listBox1.Items.Add(user.Properties["Name"].Value.ToString());
}
else
{
//Don't believe this will ever happen, but it's possible... I think. I'm still learning.
listBox1.Items.Add("result was null");
}
}
catch (Exception e)
{
//This is how I found out what was really wrong. Catching the Access Violation Exception did not work. This was returning a Null Reference message.
MessageBox.Show(e.Message(), "Error");
}
}
}
}