Reputation: 111
I seem to be having a very weird problem and I really have no idea what's going on. This is the source code I'm trying to debug
StorageFile file = await roamingFolder.GetFileAsync(filename);
string text = await FileIO.ReadTextAsync(file);
string[] shows = text.Split(new[] { ":?;" }, StringSplitOptions.None);
List<show> showslist = new List<show>();
foreach (string splitshow in shows)
{
string[] show1 = splitshow.Split(new[] { ",?;" }, StringSplitOptions.None);
episode = show1[0];
name = show1[1];
showslist.Add(new show { name = name, episode = episode });
}
Output.ItemsSource = showslist;
The weird thing is that the list is shown only if I put Output.ItemsSource = showslist;
inside of the foreach loop but not when it's outside and I really don't understand why it's not. I mean elements of the list have already been added to it haven't they??
Have tried many different methods and most of them even if they did show the list data had many different problems that are too messy to fix.
Anyway appreciate any hint or help, thank you.
Upvotes: 6
Views: 374
Reputation: 23218
I'll bet that your data isn't exactly correct. I think one of the later/last entries is throwing an exception and it's being swallowed higher up in your code (or not being reported to your logger/UI). It never completes the foreach
loop and exits the method before you can assign your data source.
I would guess that your second split, one of the entries does not actually contain your delimiter ,?;
so the show1
array is only of length 1 and does not contain a "name" entry. When you try to access show1[1]
, it throws an IndexOutOfRangeException
.
As an aside, might I suggest that you investigate using simpler delimiters, or better yet, utilize some form of XML (or JSON, or other) serialization for reading your data.
EDIT: I see from your posted code sample in your comments, that the issue is the last entry. Given hlj,?;lljhjh:?;hhmm,?;drr:?;oo,?;hello:?;ff,?;ff:?;
, your first String.Split
operation on :?;
will yield an empty string as the last entry. Thus when you try to perform your second split against ,?;
it splits against empty and returns an array with a single entry of String.Empty
. When you hit show1[1]
the exception is thrown.
If you change your first split to use StringSplitOptions.RemoveEmptyEntries
it should eliminate the empty entry:
string[] shows = text.Split(new[] { ":?;" }, StringSplitOptions.RemoveEmptyEntries);
If you like, you can add a check like if (show1.Length == 2)
then you can avoid bad data (but perhaps you would prefer to report that so you can fix it). If your program is writing this bad data itself, perhaps you should make a couple quick unit tests to ensure that you're always writing/reading valid data.
Upvotes: 9