Search code examples
c#active-directorydirectoryservices

Commiting changes on DirectoryEntry returned from using block within function


I'm going to show my ignorance about how using statements work in c# I think.

I am trying to write a function that takes in unique identifiers for a user in active directory and returns that user. I then want to make changes to the user and commit them.

I suspect this isn't working because I'm returning in a using block.

Here is the basic idea:

public static DirectoryEntry GetADUser( string prop1Value, string prop2Value )
{
    using( var rootDE = new DirectoryEntry(LDAPPath, User, Password))
    {
        using( var searcher = new DirectorySearcher(rootDE))
        {
            searcher.Filter = string.Format("(&(prop1={0})(prop2={1}))", prop1Value, prop2Value);
            var user = searcher.FindOne().GetDirectoryEntry();

            return user;
        }
    }
}

//...

var user = GetADUser("val1","val2");

user.Properties["prop3"].Value = "Spagetti";
user.CommitChanges();

Would that work? It doesn't seem like active directory is showing changes I make in that way. I'm not getting any exceptions when calling commit changes.

This is related to: Is it OK doing a return from inside using block and What happens when 'return' is called from within a 'using' block?.

If it won't work this way, how bad could it get if I rewrote that function without the using blocks?


Solution

  • declare your user as a SearchResult outside of the using blocks then assign it in the using(var searcher....) block then put your return statement after the end of the using block

    i.e

    SearchResult user = null;
    using( var rootDE = new DirectoryEntry(LDAPPath, User, Password))
    {
        using( var searcher = new DirectorySearcher(rootDE))
        {
            searcher.Filter = string.Format("(&(prop1={0})(prop2={1}))", prop1Value, prop2Value);
            var user = searcher.FindOne().GetDirectoryEntry();
    
    
        }
    }
    return user;
    

    you can also streamline things a bit by changing the searcher using block

    using (var searcher = new DirectorySearcher(rootDD, string.Format("(&(prop1={0})(prop2={1}))", prop1Value, prop2Value))
    {
        user = searcher.FindOne();
    }