![](/img/trans.png)
[英]Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
[英]Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
所以我遇到这个问题,有人试图加载没有电子邮件地址的页面,而我却很难找到解决方法。
//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语句是我最近的尝试,但错误仍然存在。
您的问题是[0]
中userObject.Properties[prop][0].ToString()
如果数组为空; 即没有元素,那么您将收到错误。 尝试
CurrentUserEmail = "";
var propertyArray = userObject.Properties[prop];
if (propertyArray.Lenght > 0) CurrentUserEmail = propertyArray[0] as string;
为什么不捕获异常并在catch块中将电子邮件地址分配给“”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.