[英]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.