C# 如何循环遍历 PropertyCollection

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/640792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:24:23  来源:igfitidea点击:

How do I loop through a PropertyCollection

c#asp.netiisdirectoryservices

提问by Michael Kniskern

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 没有 Name/Value 属性。它确实有一个 PropertyNames 和 Values,类型为 System.Collection.ICollection。我不知道构成 PropertyCollection 对象的基线对象类型。

@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));                
            }
        }      
    }  
}

采纳答案by Zhaph - Ben Duguid

The PropertyCollection has a PropertyName collection - which is a collection of strings (see PropertyCollection.Containsand PropertyCollection.Itemboth of which take a string).

PropertyCollection 有一个 PropertyName 集合 - 这是一个字符串集合(请参阅PropertyCollection.ContainsPropertyCollection.Item,两者都采用字符串)。

You can usually call GetEnumeratorto 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,然后是每个项目/值的对象。

回答by JaredPar

EDITI 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);

回答by shahkalpesh

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.

在监视窗口中查看运行时 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 组成

回答by antonioh

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

回答by Vladimir

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

回答by Vladimir

I think there's an easier way

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

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

回答by user2680296

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

如果你只想要几件物品,你真的不需要做任何神奇的事情......

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

使用语句:System、System.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;
}

回答by long2know

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 时总是遇到无效的转换异常。使用 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。

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

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

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

回答by Mohammed Othman

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;
}

回答by Bbb

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;
    }