[英]C# method to get Active Directory properties
I want to create a method which accepts two arguments; 我想创建一个接受两个参数的方法。 First being the username, and the second being the name of the Active Directory property to return... The method exists in a separate class (
SharedMethods.cs
) and works fine if you define the property name locally in the method, however I can't workout how to pass this in from the second argument. 第一个是用户名,第二个是要返回的Active Directory属性的名称...该方法存在于单独的类(
SharedMethods.cs
)中,如果您在方法中本地定义属性名称,则可以正常工作,但是我可以不要锻炼如何从第二个参数中传递出来。
Here is the method: 方法如下:
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;
}
And the code that is calling it is as follows; 调用它的代码如下:
sDisplayName = SharedMethods.GetADUserProperty(sUsername, "DisplayName");
Currently Enum.Parse
is throwing the following error: 当前
Enum.Parse
以下错误:
The non-generic method 'system.enum.parse(system.type, string, bool)' cannot be used with type arguments
非泛型方法'system.enum.parse(system.type,string,bool)'不能与类型参数一起使用
I can get it to work by removing the Enum.Parse
, and manually specifying the property to retrieve as such: 我可以通过删除
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;
}
Pretty sure I'm missing something obvious, thanks in advance for everyone's time. 可以肯定的是,我缺少明显的东西,在此先感谢大家的时间。
If you want to get the value of a property dynamically based on the property name, you will need to use reflection. 如果要基于属性名称动态获取属性的值,则需要使用反射。
Please take a look at this answer: Get property value from string using reflection in C# 请看一下这个答案: 在C#中使用反射从字符串获取属性值
Because UserPrincipal is not an enum this will be hard but as Svein suggest it is possible with reflections. 因为UserPrincipal不是枚举,所以这很困难,但是正如Svein所说的那样,可以通过反思来实现。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.