C # - OutOfMemoryException while fetching thousands of Active Directory groups

1

I'm looking for thousands of groups with hundreds of users each from Active Directory, but it's consuming a lot of memory. It starts with about 300 MB and when it reaches about 1800 MB, seen in the task manager, an OutOfMemoryException is thrown. The exception is thrown when this part of the code is being executed.

foreach (string objectGUID in listGroups)
{
    GroupDTO objGroup = new GroupDTO();

    objGroup = ADHelper.GetGroupByGUID(objectGUID, domainInfo.GeneratePathOfDomainObj(domainInfo.RootDN), domainInfo.UserName, domainInfo.Password, domainInfo.AuthType, new string[] { "distinguishedname", "name", "objectGUID", "samaccountname", "mail", "description", "whenchanged", "grouptype", "primaryGroupToken" });

    List listUsersGroup = new List();

    //Uma lista com todos os ID (ObjectGUID) do grupo atual
    listUsersGroup = ADHelper.GetUsersFromGroup(objectGUID, domainInfo.GeneratePathOfDomainObj(domainInfo.RootDN), domainInfo.UserName, domainInfo.Password, domainInfo.AuthType, new string[] { "objectguid" }, domainInfo.PropertiesGroupsAndUsers, domainInfo.RootDN);

    Dictionary dicGroup = new Dictionary();
    string jSonGroup = JsonConvert.SerializeObject(objGroup);
    dicGroup.Add("group", jSonGroup);
    dicGroup.Add("lstUser", listUsersGroup); 

    arrayListGroups.Add(dicGroup);
}
    
asked by anonymous 02.08.2017 / 18:47

1 answer

0

I've had issues with OutOfMemoryException, I've resolved putting the objects out of the loop, like this:

GroupDTO objGroup;
List listUsersGroup;
Dictionary dicGroup;
foreach (string objectGUID in listGroups)
{
    objGroup = new GroupDTO();

    objGroup = ADHelper.GetGroupByGUID(objectGUID, domainInfo.GeneratePathOfDomainObj(domainInfo.RootDN), domainInfo.UserName, domainInfo.Password, domainInfo.AuthType, new string[] { "distinguishedname", "name", "objectGUID", "samaccountname", "mail", "description", "whenchanged", "grouptype", "primaryGroupToken" });

    listUsersGroup = new List();

    //Uma lista com todos os ID (ObjectGUID) do grupo atual
    listUsersGroup = ADHelper.GetUsersFromGroup(objectGUID, domainInfo.GeneratePathOfDomainObj(domainInfo.RootDN), domainInfo.UserName, domainInfo.Password, domainInfo.AuthType, new string[] { "objectguid" }, domainInfo.PropertiesGroupsAndUsers, domainInfo.RootDN);

    dicGroup = new Dictionary();
    string jSonGroup = JsonConvert.SerializeObject(objGroup);
    dicGroup.Add("group", jSonGroup);
    dicGroup.Add("lstUser", listUsersGroup); 

    arrayListGroups.Add(dicGroup);
}
    
02.08.2017 / 19:12