我试图检索隔离存储文件中的所有数据。 但我得到索引超出范围错误。 家^如何^唷
StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("AlarmFolder\\alarm.txt", FileMode.Open, myStore));
string[] alarmDetailsSeparated;
String fileText = readFile.ReadLine();
//alarmDetailsSeparated is the array that hold the retrieved alarm details from alarm.txt and is split by '^'
alarmDetailsSeparated = fileText.Split(new char[] { '^' });
foreach (string home in alarmDetailsSeparated)
{
for (i = 0; i < alarmDetailsSeparated.Length;)
{
if (test > 0)
{
i = test;
}
dateSeparate = alarmDetailsSeparated[i];
timeSeparate = alarmDetailsSeparated[i + 1];
labelSeparate = alarmDetailsSeparated[i + 2];
date = dateSeparate;
time = timeSeparate;
label = labelSeparate;
test = test + 3 ;
break;
}
MessageBox.Show("i is " + alarmDetailsSeparated[i]);
MessageBox.Show("i + 1 is " + alarmDetailsSeparated[i + 1]);
MessageBox.Show("i + 2 is " + alarmDetailsSeparated[i + 2]);
}
答案 0 :(得分:1)
在循环中,您将从0
转到alarmDetailsSeparated
的长度。这没关系,但您可以使用alarmDetailsSeparated
和i+1
为i+2
编制索引。
这意味着当循环处于alarmDetailsSeparated.Length-2
时,程序将索引alarmDetailsSeparated.Length-2+2 = alarmDetailsSeparated.Length
并抛出越界错误。
答案 1 :(得分:1)
dateSeparate = alarmDetailsSeparated[i];
timeSeparate = alarmDetailsSeparated[i + 1];
labelSeparate = alarmDetailsSeparated[i + 2];
最后两行是有问题的:如果从0循环到alarmDetailsSeperated长度,则无法保证当前索引+ 1或+2存在,从而使此代码不安全(如您所见)正在获得例外)。
一个简单的解决方案是修改你的循环:
for (i = 0; i < alarmDetailsSeparated.Length - 2;)
答案 2 :(得分:0)
好的,IIUC你的存储文件看起来像这样:
home^date^time^label
home^date^time^label
...
并且您希望对文件中的每个警报数据条目进行处理。
您需要做的第一件事就是在每一行上拆分它:
string[] lines = file.ReadAllLines("alarms.dat");
foreach (line in lines) {
// handle the alarm data entry (see below)
}
现在,您可以像在代码中一样进行拆分:
string[] data = line.Split(new char[] { '^' });
如果该行包含您想要的数据,则应该为您提供4个条目,因此请检查:
if (data.Length == 4) { // looks like an alarm data entry
// do processing on the alarm data entry (see below)
}
现在可以提取数据:
string home = data[0];
string date = data[1];
string time = date[2];
string label = date[3];
然后采取行动:
MessageBox.Show(String.Format("home {0} at {1} on date {2} with label {3}",
home, time, date, label));