Abhinav Srivastava
Abhinav Srivastava

Reputation: 15

How to update value of a "usercert" property in LDAP AD

I have a requirement where I need to update the value saved in the property ("usercert") of a computer present in active directory.

// Retrieving properties value from AD

DirectoryEntry entry = new DirectoryEntry(LDAPPath, LDAPUser, DecryptPwd(LDAPPwd, LDAPKey)); 
DirectorySearcher searcher = new DirectorySearcher(entry); 
searcher.Filter = string.Format("(&(objectCategory=computer)(Name=" + MachineName + "))"); 
result = searcher.FindOne(); 
byte[] text= (byte[])result.GetDirectoryEntry().Properties["usercert"].Value;

// Updateing new value to AD string updatedText= "New Text";

if (result.GetDirectoryEntry().Properties["usercert"] != null && 
              result.GetDirectoryEntry().Properties["usercert"].Value != null) 
{
     byte[] updatedTextByte = Encoding.ASCII.GetBytes(updatedText);
     result.GetDirectoryEntry().InvokeSet("usercert", updatedPassByte);
     //(result.GetDirectoryEntry().Properties["usercert"]).Value = Encoding.ASCII.GetBytes(updatedText);
     //result.GetDirectoryEntry().Properties["usercert"].Add(Encoding.ASCII.GetBytes(updatedText));
     //result.GetDirectoryEntry().Properties["usercert"][0] = Encoding.ASCII.GetBytes(updatedText);
     result.GetDirectoryEntry().CommitChanges();  
}

I tried with all of the above commented code but nothing works for me. Can you please help me to solve this issue.

Upvotes: 0

Views: 270

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 41008

Calling GetDirectoryEntry() creates a new DirectoryEntry object each time you call it, which you can see in the source code here.

So when you do this:

result.GetDirectoryEntry().CommitChanges();

It's creating a brand new DirectoryEntry object and calling CommitChanges() on that. So nothing is changed.

You will need to call GetDirectoryEntry() only once and make changes to that object. For example:

var resultDe = result.GetDirectoryEntry();
resultDe.Properties["usercert"]).Value = whatever;
resuleDe.CommitChanges();

Upvotes: 0

Related Questions