Search code examples
c#arraysindexinguser-accounts

file loading error


Okay so i'm trying to load up a bunch of profiles through C# and I keep getting this error when I try to start up the program.

C:\C#FILES>program.exe

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
   at ConsoleApplication2.Program.loadAccounts()
   at ConsoleApplication2.Program.Main(String[] args)

C:\C#FILES>

i've investigated and i think it has to do with the format of the accounts in the file i'm wondering what the proper way is, i've tried every way i can think of

here's the loading accounts method

private static void loadAccounts()
{
    using (TextReader tr = new StreamReader("accounts.txt"))
    {
        string line = null;
        while ((line = tr.ReadLine()) != null)
        {
            String[] details = line.Split('\t');
            accounts.Add(details[0] + ":" + details[1]);
        }
    }
}

the accounts.txt part is the part i'm unsure about, i thought it would be as follows username(tab)password like this

username    password

however it gives the error shown above does anyone know what the proper account format should be?


Solution

  • You're getting an IndexOutOfRangeException, which suggests that details only had a single entry - which means there wasn't a tab on that line.

    I suggest you print out the line in question before splitting, so you can see which line is causing problems. Or possibly do it conditionally:

    while ((line = tr.ReadLine()) != null)
    {
        String[] details = line.Split('\t');
        if (details.Length == 1)
        {
            // Or log it, or whatever...
            Console.WriteLine("Input error: no tab in line '{0}'", line);
        }
        else
        {
            accounts.Add(details[0] + ":" + details[1]);
        }
    }