指数超出范围。必须是非负数且小于集合的大小。参数名称:index

时间:2013-11-08 15:01:54

标签: c# asp.net active-directory

所以我遇到了这个问题,有人试图加载这个没有电子邮件地址的页面,而且我很难找到一个解决方法。

//getting email address for current user
    IIdentity id = WindowsIdentity.GetCurrent();
    WindowsIdentity winId = id as WindowsIdentity;
    if (id != null)
    {
        userName = winId.Name;

        string userInQuestion = userName.Split('\\')[1];
        string myDomain = userName.Split('\\')[0]; // this is the domain that the user is in
        // the account that this program runs in should be authenticated in there                    

        using (HostingEnvironment.Impersonate())
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
            DirectorySearcher adSearcher = new DirectorySearcher(entry);

            adSearcher.SearchScope = SearchScope.Subtree;
            adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
            SearchResult userObject = adSearcher.FindOne();
            if (userObject != null)
            {
                string[] props = new string[] { "mail"};
                {
                    foreach (string prop in props)
                    {
                        if (userObject.Properties[prop][0].ToString() != "")
                        {
                            CurrentUserEmail = userObject.Properties[prop][0].ToString();
                        }
                        else
                        {
                            CurrentUserEmail = "";
                        }
                    }

                }
            }

        }
    }

这是我得到的堆栈跟踪,我知道提交此表单的某些人可能没有电子邮件地址,但我似乎无法找到解决问题的方法。 if else语句是我最近的尝试,但错误仍然存​​在。

enter image description here

2 个答案:

答案 0 :(得分:3)

您的问题是[0]

中的userObject.Properties[prop][0].ToString()

如果数组为空;即没有元素,你会收到错误。 尝试

CurrentUserEmail = "";
var propertyArray = userObject.Properties[prop];
if (propertyArray.Lenght > 0) CurrentUserEmail = propertyArray[0] as string;

答案 1 :(得分:0)

为什么不捕获异常并在catch块中将电子邮件地址分配给“”?