Bill Greer
Bill Greer

Reputation: 3156

C# Active Directory Group Querying

I am trying the code found here.

I am getting the following compile time error:

The name 'p' does not exist in the current context

Here is my code...can someone help? Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

 public static List<string> GetGroups()
 {
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
     {
         using (p = Principal.FindByIdentity(ctx, "yourUserName")) 
         {
            var groups = p.GetGroups();
            using (groups)
            {
                foreach (Principal group in groups)
                {
                    Console.WriteLine(group.SamAccountName + "-" + group.DisplayName); 
                } 
            }
        }
     } 
 }

Upvotes: 2

Views: 674

Answers (3)

squillman
squillman

Reputation: 13641

You never declare p.

Try this:

using (var p = Principal.FindByIdentity(ctx, "yourUserName"))

Upvotes: 1

marc_s
marc_s

Reputation: 754478

You need to define a type for your variable p:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
using (Principal p = Principal.FindByIdentity(ctx, "yourUserName")) 
{
    var groups = p.GetGroups();

    foreach (Principal group in groups)
    {
        Console.WriteLine(group.SamAccountName + "-" + group.DisplayName); 
    } 
}

PS: Sorry, that code you use was created by me in response to another question - and I had this error in there. Sorry for that - it's been fixed now. Thanks for pointing that out!

Upvotes: 1

Garrett Vlieger
Garrett Vlieger

Reputation: 9494

You never declare p. You need to change the code to this:

// Add a "var" below
using (var p = Principal.FindByIdentity(ctx, "yourUserName")) 

Upvotes: 3

Related Questions