1

I have a .txt file that is setup like this:

1 Username Email MD5Password PlainPassword

Now I want to put this .txt into SQL, so I have this code:

string[] SQL = line.Split(' ');

dynamic ID = SQL[0];
dynamic Username = SQL[1];
dynamic Email = SQL[2];
dynamic Password = SQL[3];
dynamic PlainPassword = SQL[4];

string lines = "INSERT INTO `dbsearch`(`username`, `password`, `email`, `extra`) VALUES ('" + Username + "', '" + Password + "', '" + Email + "', '" + PlainPassword + "')";

But some lines in my .txt file doesnt have a password or plainpassword, so I get this error:

Exception thrown: 'System.IndexOutOfRangeException' in Search SQL Creator.exe

Additional information: Index was outside the bounds of the array.

How can I fix this?

6
  • 1
    What don't you understand about the error message? You're accessing an index which is outside the bounds of your array. Are you sure you have 5 elements? Commented Oct 11, 2015 at 12:02
  • You can run the debugger and add a breakpoint at the first line. Please show the content of "SQL" at the execution. Commented Oct 11, 2015 at 12:02
  • Like I said, most of the times I have 5 elements, but sometimes there is not. So how can I just make it empty if there is not a element? Commented Oct 11, 2015 at 12:03
  • just check the size of SQL, and if it contains 5 values do as now, and if only 3 set default values for P and PP. Commented Oct 11, 2015 at 12:08
  • Why are you using dynamic when the values are clearly string? Commented Oct 11, 2015 at 13:47

2 Answers 2

4

If you're not sure whether you have the last element, you can check before accessing it inside the array:

string[] sql = line.Split(' ');

dynamic id = sql[0];
dynamic username = sql[1];
dynamic email = sql[2];
dynamic password = sql.Length >= 4 ? sql[3] : null;
dynamic plainPassword = sql.Length == 5 ? sql[4] : null;
Sign up to request clarification or add additional context in comments.

Comments

0

You could also use LINQ:

string[] sql = line.Split(' ');

string id = sql[0];
string username = sql[1];
string email = sql[2];
string password = sql.Skip(3).FirstOrDefault();
string plainPassword = sql.Skip(4).FirstOrDefault();

2 Comments

This would redundantly enumerate the collection twice.
@YuvalItzchakov - Possibly. At worst though this is only for 7 + 2 elements. Accessing 9 elements to get 2 from an array is hardly a performance issue. Besides, many of the LINQ operators recognize that they are iterating over arrays and do direct access.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.