2014-10-16 112 views
0

我想創建一個接受兩個參數的方法;第一個是用戶名,第二個是要返回的Active Directory屬性的名稱...該方法存在於單獨的類(SharedMethods.cs)中,如果在方法中本地定義屬性名稱,則工作正常,但是我無法鍛鍊如何從第二個參數中傳入。獲取Active Directory屬性的C#方法

這裏是方法:

public static string GetADUserProperty(string sUser, string sProperty) 
{  
     PrincipalContext Domain = new PrincipalContext(ContextType.Domain); 
     UserPrincipal User = UserPrincipal.FindByIdentity(Domain, sUser); 

     var Property = Enum.Parse<UserPrincipal>(sProperty, true); 

     return User != null ? Property : null; 
} 

和被調用它是如下的代碼;

sDisplayName = SharedMethods.GetADUserProperty(sUsername, "DisplayName"); 

目前Enum.Parse拋出以下錯誤:

The non-generic method 'system.enum.parse(system.type, string, bool)' cannot be used with type arguments

我可以得到它通過移除Enum.Parse,並且手動指定屬性的工作來獲取這樣:

public static string GetADUserProperty(string sUser, string sProperty) 
{ 
     PrincipalContext Domain = new PrincipalContext(ContextType.Domain); 
     UserPrincipal User = UserPrincipal.FindByIdentity(Domain, sUser); 

     return User != null ? User.DisplayName : null; 
} 

很確定我錯過了一些顯而易見的東西,在此先感謝大家的時間。

回答

0

因爲UserPrincipal不是一個枚舉,這將是很難,但作爲斯韋恩暗示有可能與思考。

public static string GetAdUserProperty(string sUser, string sProperty) 
{ 
    var domain = new PrincipalContext(ContextType.Domain); 
    var user = UserPrincipal.FindByIdentity(domain, sUser); 

    var property = GetPropValue(user, sProperty); 

    return (string) (user != null ? property : null); 
} 

public static object GetPropValue(object src, string propName) 
{ 
    return src.GetType().GetProperty(propName).GetValue(src, null); 
} 
+0

感謝Piazzolla,正是我正在尋找的東西,這個例子特別有用,因爲我按照Svein的建議正在努力爭取我的頭腦。 – jamesmealing 2014-11-03 12:50:47

相關問題