How to get Active Directory connection string in C#.NET

How to get Active Directory connection string in C#.NET

First you will have to add a reference for System.DirectoryServices
You must run the application on a machine within the same domain to be able to connect to the Active Directory

using System.DirectoryServices;

private string GetActiveDirectoryConnectionString()
  DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
  using (root)
    string dnc = root.Properties["defaultNamingContext"][0].ToString();
    string server = root.Properties["dnsHostName"][0].ToString();
    string adsPath = String.Format("LDAP://{0}/{1}", server, dnc);
  return adsPath;

Share this post

Comment (1)

  • Olivia Wright Reply

    I want to thank the author for publishing this piece, which serves as a useful reference for developers who need to connect to Active Directory in their C#.NET apps. The procedures for acquiring the connection string necessary for connecting to Active Directory using C# code are thoroughly explained in the post.

    Also, I found the code examples in the text to be simple and succinct. The author has done an excellent job of explaining what each line of code does, making it simple for readers to comprehend the process.

    May 15, 2023 at 8:57 AM

Leave a Reply

Your email address will not be published. Required fields are marked *