Fixing Active Directory Error Logon Failure - Unknown User Name Or Bad Password

Fixing System.DirectoryServices.DirectoryServicesCOMException (0x8007052E): Logon failure: unknown user name or bad password.

Recently I faced a weird issue where I was not able to run the LDAP queries using Directory Services API of .Net for other domains through legitmate user accounts. 
 
If I was logged into Domain xyz.com, and I was able to run the LDAP queries in xyz.com domain,  I was not able to run the queries on abc.com AD from xyz.com.
 
After digging and running through a few links, here is the code change that helped me fix the issue.

Before 

Check the DirectoryEntry Path properties, it's set with direct ad domain.  
  1. using (DirectoryEntry rootEntry = new DirectoryEntry())  
  2.             {  
  3.                 rootEntry.Path = $"LDAP://dc=abc,dc=com";  
  4.                 rootEntry.Username = yourid;  
  5.                 rootEntry.Password = yourpassword;   
  6.                   
  7.                 using (DirectorySearcher _searcher = new DirectorySearcher(rootEntry))  
  8.                 {  
  9.                     _searcher.Filter = filter;  
  10.                     _searcher.PageSize = 1000;  
  11.   
  12.                     
  13.                    SearchResultCollection _searchResultCollections = _searcher.FindAll();  
  14.                 }  
  15.             }  

Fix

Changing the DirectoryEntry Path to explictly connect to the 389 port fixed the issue.
  1. rootEntry.Path = $"LDAP://abc.com:389/dc=abc,dc=com";  
Here is the MSDN article that explains in detail how the lDAP query search works, that gave me some hints. 
 
Happy coding.