views:

70

answers:

1

I have a WPF program built in C#, and part of it's function is populating two ListBox controls. At the Window_Loaded event the program calls the Update() function in order to populate the ListBoxes, but it only executes part of the function. And if I call the function after an append has been made to the file, the function will even crash. The file is structured as follows :

content_for_first_listbox content_for_second_listbox

The function Update is as follows :

private void UpdateURL()
{
    StreamReader rdr = new StreamReader("Links.db");
    string line;
    int dummy;
    URL.Clear();
    TAGS.Clear();
    while ((line = rdr.ReadLine()) != null)
    {
        dummy = line.IndexOf(' ');
        URL.Add(line.Substring(0, dummy));
        TAGS.Add(line.Substring(dummy + 1));
    }
    rdr.Close();
    LLinks.Items.Clear();
    LTags.Items.Clear();
    for (int a = 0; a < URL.Count; a++)
    {
        LLinks.Items.Add(new ListBoxItem().Content = URL[a]);
        LTags.Items.Add(new ListBoxItem().Content = TAGS[a]);
    }
}

It stops executing after the first loop, I found that out from debugging. And here is the append function

private void LBookmarkBT_Click(object sender, RoutedEventArgs e)
{
    StreamWriter wrt = new StreamWriter("Links.db", true);
    wrt.Write("\n" + LURLTBox.Text + " " + LTagsTBox.Text);
    wrt.Close();
    UpdateURL();
}

Any ideas ?

Update : The problem is that it was reading the all the lines and parsed them correctly but then it would read a newline out of nowhere, the line string became "" and therefore dummy = -1 and it threw a length exception. I managed to overcome this by putting the loop in a try-catch block and discarding the exception, and everything works fine, but it seems kind of, "dirty" if I may say so. What should I do ? Perhaps and if(dummy == -1) don't parse the line ?

        try
        {
            while ((line = rdr.ReadLine()) != null)
            {
                dummy = line.IndexOf(' ');
                URL.Add(line.Substring(0, dummy));
                TAGS.Add(line.Substring(dummy + 1));
            }
        }
        catch (Exception e)
        { }
+4  A: 

Try running with "Break when an exception is thrown" enabled in the Exceptions dialog (Ctrl+Alt+E in VS.Net / Debug\Exceptions... menu option). This should break the debugger when an exception is thrown - which is almost certainly what you're getting here.

Will A
It helped a lot in the debugging, thanks.
Andrew