简体   繁体   中英

Index was outside the bounds of the array in - C#

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?

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;

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM