2011-11-30 48 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"))