GetFiles上的IndexOutOfRange

时间:2018-07-11 08:59:46

标签: c# arrays dictionary indexoutofrangeexception getfiles

我正在尝试读取大量文件并将某些信息存储在字典中。我完整的代码是:

[HttpGet("[action]")]

public JsonResult GenerateMapFiles()
{
    Dictionary<string, List<Tuple<string, ushort>>>[] CodeMapping = new Dictionary<string, List<Tuple<string, ushort>>>[256];

    /* Pre-creating some dictionaries */
    CodeMapping[2] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[8] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[16] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[32] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[64] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[128] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[256] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);

    string[] fileList = System.IO.Directory.GetFiles("C:\\mySQL");

    /* Processing code was here, but I commented it and it is still generating exception */

    return Json(CodeMapping);
}

string[] fileList = System.IO.Directory.GetFiles("C:\\mySQL");行引发异常:

Exception thrown: 'System.IndexOutOfRangeException' in XXXXX.dll: 'Index was outside the bounds of the array.'

如果我注释CodeMapping [X]分配,则没有错误,并且将填充fileList。我不明白为什么前几行会影响这一行。 有人可以向我解释原因吗?

2 个答案:

答案 0 :(得分:0)

好的,我在提交时找到了解决方案,这显然是Visual Studio的一个错误,它没有在调试模式下指向正确的行。我的第一行应该是:

Dictionary<string, List<Tuple<string, ushort>>>[] CodeMapping = new Dictionary<string, List<Tuple<string, ushort>>>[257];

答案 1 :(得分:0)

我认为您应该在n-1个位置上创建字典,因为如果集合有256个元素,则最大索引将从0到255。

因此您将其重写为:

/* Pre-creating some dictionaries */
    CodeMapping[1] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[7] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[15] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[31] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[63] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[127] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
    CodeMapping[255] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);