Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取Active Directory属性的C方法_C#_Active Directory - Fatal编程技术网

C# 获取Active Directory属性的C方法

C# 获取Active Directory属性的C方法,c#,active-directory,C#,Active Directory,我想创建一个接受两个参数的方法;第一个是用户名,第二个是要返回的Active Directory属性的名称。。。该方法存在于一个单独的类SharedMethods.cs中,如果在该方法中本地定义属性名称,则该方法可以正常工作,但是我无法确定如何从第二个参数传入该属性 方法如下: public static string GetADUserProperty(string sUser, string sProperty) { PrincipalContext Domain =

我想创建一个接受两个参数的方法;第一个是用户名,第二个是要返回的Active Directory属性的名称。。。该方法存在于一个单独的类SharedMethods.cs中,如果在该方法中本地定义属性名称,则该方法可以正常工作,但是我无法确定如何从第二个参数传入该属性

方法如下:

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;
}
当前Enum.Parse正在引发以下错误:

非泛型方法“system.enum.parsesystem.type,string,bool”不能与类型参数一起使用

我可以通过删除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;
}

非常肯定我遗漏了一些明显的东西,提前感谢大家的时间。

如果您希望根据属性名称动态获取属性值,则需要使用反射


请看下面的答案:

因为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);
}

谢谢Piazzolla,这正是我想要的,这个例子非常有用,因为我正努力按照Svein的建议思考。也谢谢你的回答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);
}