如何循环遍历PropertyCollection

时间:2022-10-30 10:23:58

Can anyone provide an example of how to loop through a System.DirectoryServices.PropertyCollection and output the property name and value?

任何人都可以提供如何在System.DirectoryServices中循环的示例吗?PropertyCollection并输出属性名称和值?

I am using C#.

我使用c#。

@JaredPar - The PropertyCollection does not have a Name/Value property. It does have a PropertyNames and Values, type System.Collection.ICollection. I do not know the basline object type that makes up the PropertyCollection object.

@JaredPar - PropertyCollection没有名称/值属性。它有一个属性名和值,类型System.Collection.ICollection。我不知道组成PropertyCollection对象的basline对象类型。

@JaredPar again - I originally mislabeled the question with the wrong type. That was my bad.

@JaredPar -我最初错误地给问题贴上了错误的标签。这是我的坏。

Update: Based on Zhaph - Ben Duguid input, I was able to develop the following code.

更新:基于Zhaph - Ben Duguid输入,我可以开发以下代码。

using System.Collections;
using System.DirectoryServices;

public void DisplayValue(DirectoryEntry de)
{
    if(de.Children != null)
    {
        foreach(DirectoryEntry child in de.Children)
        {
            PropertyCollection pc = child.Properties;
            IDictionaryEnumerator ide = pc.GetEnumerator();
            ide.Reset();
            while(ide.MoveNext())
            {
                PropertyValueCollection pvc = ide.Entry.Value as PropertyValueCollection;

                Console.WriteLine(string.Format("Name: {0}", ide.Entry.Key.ToString()));
                Console.WriteLine(string.Format("Value: {0}", pvc.Value));                
            }
        }      
    }  
}

10 个解决方案

#1


5  

The PropertyCollection has a PropertyName collection - which is a collection of strings (see PropertyCollection.Contains and PropertyCollection.Item both of which take a string).

PropertyCollection有一个PropertyName集合——它是字符串的集合(参见PropertyCollection)。包含和PropertyCollection。项都取一个字符串)。

You can usually call GetEnumerator to allow you to enumerate over the collection, using the usual enumeration methods - in this case you'd get an IDictionary containing the string key, and then an object for each item/values.

您通常可以调用GetEnumerator,以便使用通常的枚举方法对集合进行枚举——在本例中,您将获得一个包含字符串键的IDictionary,然后是每个项/值的对象。

#2


25  

See the value of PropertyValueCollection at runtime in the watch window to identify types of element, it contains & you can expand on it to further see what property each of the element has.

请在watch窗口中查看PropertyValueCollection在运行时的值,以标识元素的类型,它包含&您可以在其上展开,以进一步查看每个元素具有什么属性。

Adding to @JaredPar's code

增加@JaredPar的代码


PropertyCollection collection = GetTheCollection();
foreach ( PropertyValueCollection value in collection ) {
  // Do something with the value
  Console.WriteLine(value.PropertyName);
  Console.WriteLine(value.Value);
  Console.WriteLine(value.Count);
}

EDIT: PropertyCollection is made up of PropertyValueCollection

编辑:PropertyCollection由PropertyValueCollection组成

#3


4  

usr = result.GetDirectoryEntry();
foreach (string strProperty in usr.Properties.PropertyNames)
{
   Console.WriteLine("{0}:{1}" ,strProperty, usr.Properties[strProperty].Value);
}

#4


2  

foreach(var k in collection.Keys) 
{
     string name = k;
     string value = collection[k];
}

#5


0  

EDIT I misread the OP as having said PropertyValueCollection not PropertyCollection. Leaving post up because other posts are referenceing it.

编辑我误读了OP,因为我说了PropertyValueCollection而不是PropertyCollection。因为其他的帖子在引用它而离开。

I'm not sure I understand what you're asking Are you just wanting to loop through each value in the collection? If so this code will work

我不太明白你在问什么你只是想循环遍历集合中的每个值吗?如果这样的话,这段代码就可以工作了。

PropertyValueCollection collection = GetTheCollection();
foreach ( object value in collection ) {
  // Do something with the value
}

Print out the Name / Value

打印出名称/值

Console.WriteLine(collection.Name);
Console.WriteLine(collection.Value);

#6


0  

I think there's an easier way

我认为有一个更简单的方法

foreach (DictionaryEntry e in child.Properties) 
{
    Console.Write(e.Key);
    Console.Write(e.Value);
}

#7


0  

You really don't have to do anything magical if you want just a few items...

如果你只想要一些东西,你真的不需要做什么神奇的事情……

Using Statements: System, System.DirectoryServices, and System.AccountManagement

使用语句:系统,系统。DirectoryServices,System.AccountManagement

public void GetUserDetail(string username, string password)
{
    UserDetail userDetail = new UserDetail();
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "mydomain.com", username, password);

        //Authenticate against Active Directory
        if (!principalContext.ValidateCredentials(username, password))
        {
            //Username or Password were incorrect or user doesn't exist
            return userDetail;
        }

        //Get the details of the user passed in
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, principalContext.UserName);

        //get the properties of the user passed in
        DirectoryEntry directoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry;

        userDetail.FirstName = directoryEntry.Properties["givenname"].Value.ToString();
        userDetail.LastName = directoryEntry.Properties["sn"].Value.ToString();
    }
    catch (Exception ex)
    {
       //Catch your Excption
    }

    return userDetail;
}

#8


0  

I posted my answer on another thread, and then found this thread asking a similar question.

我把我的答案贴在另一个帖子上,然后发现这个帖子问了一个类似的问题。

I tried the suggested methods, but I always get an invalid cast exception when casting to DictionaryEntry. And with a DictionaryEntry, things like FirstOrDefault are funky. So, I simply do this:

我尝试了建议的方法,但在强制转换到DictionaryEntry时,总是会得到一个无效的强制转换异常。有了字典条目,像FirstOrDefault这样的东西就很时髦了。我只是这么做:

var directoryEntry = adUser.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.RefreshCache();
var propNames = directoryEntry.Properties.PropertyNames.Cast<string>();
var props = propNames
    .Select(x => new { Key = x, Value = directoryEntry.Properties[x].Value.ToString() })
    .ToList();

With that in place, I can then easily query for any property directly by Key. Using the coalesce and safe navigation operators allows for defaulting to an empty string or whatever..

这样,我就可以通过Key直接查询任何属性。使用合并和安全导航操作符,允许默认为空字符串或其他。

var myProp = props.FirstOrDefault(x => x.Key == "someKey"))?.Value ?? string.Empty;

And if I wanted to look over all props, it's a similar foreach.

如果我想看所有的道具,每个都是一样的。

foreach (var prop in props)
{
     Console.WriteLine($"{prop.Key} - {prop.Value}");
}

Note that the "adUser" object is the UserPrincipal object.

注意,“adUser”对象是UserPrincipal对象。

#9


0  

public string GetValue(string propertyName, SearchResult result)
{
    foreach (var property in result.Properties)
    {
        if (((DictionaryEntry)property).Key.ToString() == propertyName)
        {
            return ((ResultPropertyValueCollection)((DictionaryEntry)property).Value)[0].ToString();
        }
    }
    return null;
}

#10


0  

I'm not sure why this was so hard to find an answer to, but with the below code I can loop through all of the properties and pull the one I want and reuse the code for any property. You can handle the directory entry portion differently if you want

我不知道为什么这很难找到答案,但是有了下面的代码,我可以遍历所有属性并提取我想要的属性,并为任何属性重用代码。如果需要,可以以不同的方式处理目录条目部分

getAnyProperty("[servername]", @"CN=[cn name]", "description");

   public List<string> getAnyProperty(string originatingServer, string distinguishedName, string propertyToSearchFor)
    {
        string path = "LDAP://" + originatingServer + @"/" + distinguishedName;
        DirectoryEntry objRootDSE = new DirectoryEntry(path, [Username], [Password]);
// DirectoryEntry objRootDSE = new DirectoryEntry();

        List<string> returnValue = new List<string>();
        System.DirectoryServices.PropertyCollection properties = objRootDSE.Properties;
        foreach (string propertyName in properties.PropertyNames)
        {
            PropertyValueCollection propertyValues = properties[propertyName];
            if (propertyName == propertyToSearchFor)
            {
                foreach (string propertyValue in propertyValues)
                {
                    returnValue.Add(propertyValue);
                }
            }
        }

        return returnValue;
    }

#1


5  

The PropertyCollection has a PropertyName collection - which is a collection of strings (see PropertyCollection.Contains and PropertyCollection.Item both of which take a string).

PropertyCollection有一个PropertyName集合——它是字符串的集合(参见PropertyCollection)。包含和PropertyCollection。项都取一个字符串)。

You can usually call GetEnumerator to allow you to enumerate over the collection, using the usual enumeration methods - in this case you'd get an IDictionary containing the string key, and then an object for each item/values.

您通常可以调用GetEnumerator,以便使用通常的枚举方法对集合进行枚举——在本例中,您将获得一个包含字符串键的IDictionary,然后是每个项/值的对象。

#2


25  

See the value of PropertyValueCollection at runtime in the watch window to identify types of element, it contains & you can expand on it to further see what property each of the element has.

请在watch窗口中查看PropertyValueCollection在运行时的值,以标识元素的类型,它包含&您可以在其上展开,以进一步查看每个元素具有什么属性。

Adding to @JaredPar's code

增加@JaredPar的代码


PropertyCollection collection = GetTheCollection();
foreach ( PropertyValueCollection value in collection ) {
  // Do something with the value
  Console.WriteLine(value.PropertyName);
  Console.WriteLine(value.Value);
  Console.WriteLine(value.Count);
}

EDIT: PropertyCollection is made up of PropertyValueCollection

编辑:PropertyCollection由PropertyValueCollection组成

#3


4  

usr = result.GetDirectoryEntry();
foreach (string strProperty in usr.Properties.PropertyNames)
{
   Console.WriteLine("{0}:{1}" ,strProperty, usr.Properties[strProperty].Value);
}

#4


2  

foreach(var k in collection.Keys) 
{
     string name = k;
     string value = collection[k];
}

#5


0  

EDIT I misread the OP as having said PropertyValueCollection not PropertyCollection. Leaving post up because other posts are referenceing it.

编辑我误读了OP,因为我说了PropertyValueCollection而不是PropertyCollection。因为其他的帖子在引用它而离开。

I'm not sure I understand what you're asking Are you just wanting to loop through each value in the collection? If so this code will work

我不太明白你在问什么你只是想循环遍历集合中的每个值吗?如果这样的话,这段代码就可以工作了。

PropertyValueCollection collection = GetTheCollection();
foreach ( object value in collection ) {
  // Do something with the value
}

Print out the Name / Value

打印出名称/值

Console.WriteLine(collection.Name);
Console.WriteLine(collection.Value);

#6


0  

I think there's an easier way

我认为有一个更简单的方法

foreach (DictionaryEntry e in child.Properties) 
{
    Console.Write(e.Key);
    Console.Write(e.Value);
}

#7


0  

You really don't have to do anything magical if you want just a few items...

如果你只想要一些东西,你真的不需要做什么神奇的事情……

Using Statements: System, System.DirectoryServices, and System.AccountManagement

使用语句:系统,系统。DirectoryServices,System.AccountManagement

public void GetUserDetail(string username, string password)
{
    UserDetail userDetail = new UserDetail();
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "mydomain.com", username, password);

        //Authenticate against Active Directory
        if (!principalContext.ValidateCredentials(username, password))
        {
            //Username or Password were incorrect or user doesn't exist
            return userDetail;
        }

        //Get the details of the user passed in
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, principalContext.UserName);

        //get the properties of the user passed in
        DirectoryEntry directoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry;

        userDetail.FirstName = directoryEntry.Properties["givenname"].Value.ToString();
        userDetail.LastName = directoryEntry.Properties["sn"].Value.ToString();
    }
    catch (Exception ex)
    {
       //Catch your Excption
    }

    return userDetail;
}

#8


0  

I posted my answer on another thread, and then found this thread asking a similar question.

我把我的答案贴在另一个帖子上,然后发现这个帖子问了一个类似的问题。

I tried the suggested methods, but I always get an invalid cast exception when casting to DictionaryEntry. And with a DictionaryEntry, things like FirstOrDefault are funky. So, I simply do this:

我尝试了建议的方法,但在强制转换到DictionaryEntry时,总是会得到一个无效的强制转换异常。有了字典条目,像FirstOrDefault这样的东西就很时髦了。我只是这么做:

var directoryEntry = adUser.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.RefreshCache();
var propNames = directoryEntry.Properties.PropertyNames.Cast<string>();
var props = propNames
    .Select(x => new { Key = x, Value = directoryEntry.Properties[x].Value.ToString() })
    .ToList();

With that in place, I can then easily query for any property directly by Key. Using the coalesce and safe navigation operators allows for defaulting to an empty string or whatever..

这样,我就可以通过Key直接查询任何属性。使用合并和安全导航操作符,允许默认为空字符串或其他。

var myProp = props.FirstOrDefault(x => x.Key == "someKey"))?.Value ?? string.Empty;

And if I wanted to look over all props, it's a similar foreach.

如果我想看所有的道具,每个都是一样的。

foreach (var prop in props)
{
     Console.WriteLine($"{prop.Key} - {prop.Value}");
}

Note that the "adUser" object is the UserPrincipal object.

注意,“adUser”对象是UserPrincipal对象。

#9


0  

public string GetValue(string propertyName, SearchResult result)
{
    foreach (var property in result.Properties)
    {
        if (((DictionaryEntry)property).Key.ToString() == propertyName)
        {
            return ((ResultPropertyValueCollection)((DictionaryEntry)property).Value)[0].ToString();
        }
    }
    return null;
}

#10


0  

I'm not sure why this was so hard to find an answer to, but with the below code I can loop through all of the properties and pull the one I want and reuse the code for any property. You can handle the directory entry portion differently if you want

我不知道为什么这很难找到答案,但是有了下面的代码,我可以遍历所有属性并提取我想要的属性,并为任何属性重用代码。如果需要,可以以不同的方式处理目录条目部分

getAnyProperty("[servername]", @"CN=[cn name]", "description");

   public List<string> getAnyProperty(string originatingServer, string distinguishedName, string propertyToSearchFor)
    {
        string path = "LDAP://" + originatingServer + @"/" + distinguishedName;
        DirectoryEntry objRootDSE = new DirectoryEntry(path, [Username], [Password]);
// DirectoryEntry objRootDSE = new DirectoryEntry();

        List<string> returnValue = new List<string>();
        System.DirectoryServices.PropertyCollection properties = objRootDSE.Properties;
        foreach (string propertyName in properties.PropertyNames)
        {
            PropertyValueCollection propertyValues = properties[propertyName];
            if (propertyName == propertyToSearchFor)
            {
                foreach (string propertyValue in propertyValues)
                {
                    returnValue.Add(propertyValue);
                }
            }
        }

        return returnValue;
    }