I m trying to retrieve all the data in the isolated s开发者_如何学运维torage file. But i get a index out of range error. home^how^yo^
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]);
}
In the loop, you are going from 0
to the length of alarmDetailsSeparated
. This is fine, but you are then indexing alarmDetailsSeparated
using i+1
and i+2
.
This means that when the loop is at alarmDetailsSeparated.Length-2
the program will index alarmDetailsSeparated.Length-2+2 = alarmDetailsSeparated.Length
and throw an out of bounds error.
dateSeparate = alarmDetailsSeparated[i];
timeSeparate = alarmDetailsSeparated[i + 1];
labelSeparate = alarmDetailsSeparated[i + 2];
The last 2 lines are the problematic ones: if you are looping from 0 to alarmDetailsSeperated length, there is no guarantee that the current index + 1, or +2 exists, thus making this code not safe (as you see, you are getting an exception).
An easy solution would be to modify your loop:
for (i = 0; i < alarmDetailsSeparated.Length - 2;)
Ok, IIUC your storage file looks something like this:
home^date^time^label
home^date^time^label
...
and you want to do processing on each alarm data entry in the file.
The first thing you need to do is split it on each line:
string[] lines = file.ReadAllLines("alarms.dat");
foreach (line in lines) {
// handle the alarm data entry (see below)
}
Now you can do the split as you are doing in your code:
string[] data = line.Split(new char[] { '^' });
This should give you 4 entries if the line has the data you want, so check for this:
if (data.Length == 4) { // looks like an alarm data entry
// do processing on the alarm data entry (see below)
}
the data can now be extracted:
string home = data[0];
string date = data[1];
string time = date[2];
string label = date[3];
And then acted on:
MessageBox.Show(String.Format("home {0} at {1} on date {2} with label {3}",
home, time, date, label));
精彩评论