2011-11-30 67 views
2

我在找的代码hereC#活动目录组查询

我收到以下编译时错误:

“P”不会在目前情况下

这里是我的代码...有人可以帮助存在的名字吗?谢谢。

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); 
       } 
      } 
     } 
    } 
} 
+0

对不起,您使用的代码是由我在回答另一个问题时创造的 - 我在那里有这个错误。对不起 - 现在已经修好了。感谢您指出了这一点! –

回答

3

你从不声明p。您需要将代码改成这样:

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

您需要定义一个类型为你的变量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:很抱歉,您使用的代码是由我在响应创建另一个问题 - 我在那里有这个错误。对不起 - 现在已经修好了。感谢您指出了这一点!

+1

嘿,它被称为“填充统计”! :) – squillman

1

你从不声明p

试试这个:

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