2014-10-16 114 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

相关问题