2012-07-11 28 views
0

我有一種方法,它使用.NET成員資格提供程序爲使用配置文件提供程序的每個用戶檢索一些數據。不過,我的應用程序日誌中出現錯誤,說明爲什麼這個方法返回的索引超出了數組的範圍

方法GetUsers():索引超出了數組的範圍。

「在方法GetUsers()」由我的記錄機制添加。其餘的完全是.NET。

protected Dictionary<string, string> Getusers() 
{ 
    try 
    { 
     Dictionary<string, string> userDictionary = new Dictionary<string, string>(); 

     //Get string array of users in role from RoleProvider 
     var users = Roles.GetUsersInRole("MyRoleName"); 

     //loop through the array of usernames 
     foreach (string user in users) 
     { 
      //Get user's first name and last name from the profile provider 
      ProfileCommon profile = (ProfileCommon)ProfileCommon.Create(user); 

      //add new key value pair with user name as the key and lastname,firstname as value 
      userDictionary.Add(user, string.Concat(profile.LastName + ",", profile.FirstName)); 
     } 

     //sort the dictionary by the value not the key 
     //a little linq to do the sorting 
     var sortedDict = (from entry in userDictionary orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value); 

     return sortedDict; 
    } 
    catch (Exception ex) 
    { 
     LogController.LogError("In Method -- Getusers() --" + ex.Message); 
     //if error occurs return empty dictionary 
     return new Dictionary<string, string>(); 
    } 
} 
+0

哪一行確切地拋出異常? – 2012-07-11 19:26:34

+1

你在折騰你的調用堆棧,它可以告訴你錯誤實際生成的位置。將ex.Message更改爲ex.ToString()並查看。 – MNGwinn 2012-07-11 19:27:17

+1

查看代碼,您必須實際記錄異常,即使在'Roles.GetUsersInRole'或'ProfileCommon.CreateUser'中,即在'GetUsers'方法調用的方法之一中,也可能會引發異常。我會添加一個堆棧跟蹤日誌記錄,以便您可以捕獲代碼中出現錯誤的實際行。 – 2012-07-11 19:29:16

回答

0

你確定你在userDictionary中有值嗎?

我不知道這是代碼,您看到異常

var sortedDict = (from entry in userDictionary orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value); 

如果您張貼堆棧跟蹤它會更容易知道就行了。

相關問題