Index was outside of the bounds of the array 向数据库插入数据时出现错误

Index was outside the bounds of the array error occur when insert data to a database

我正在尝试将文本文件数据插入 sql 服务器数据库,这是我的示例代码,当我执行此代码时,只有文本文件 (10,sac,10 hung vuong) 的第一行保存到数据库并且发生此错误

System.IndexOutOfRangeException was unhandled
Index was outside the bounds of the array.

示例文本文件

10,sac,10 hung vuong

11,mad,11 Hung call

22,wick,22 Hung poll

这是我的代码

string line;

using (SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=texttodb;Integrated Security=True"))
    {
        con.Open();
        using (StreamReader file = new StreamReader(@"E:\a.txt"))
        {
            while((line = file.ReadLine()) != null)
                {
                    string[] fields = line.Split(',');

                    SqlCommand cmd = new SqlCommand("INSERT INTO tblUser(id, name, address) VALUES (@id, @name, @address)", con);
                    cmd.Parameters.AddWithValue("@id", fields[0].ToString());
                    cmd.Parameters.AddWithValue("@name", fields[1].ToString());
                    cmd.Parameters.AddWithValue("@address", fields[2].ToString());
                    cmd.ExecuteNonQuery();
                }
        }
    }

好吧,如果这是准确的文本文件

10,sac,10 hung vuong

11,mad,11 Hung call

22,wick,22 Hung poll

每行数据之间有空行。将文件编辑为:

10,sac,10 hung vuong    
11,mad,11 Hung call    
22,wick,22 Hung poll

或者放一个条件

 if (line.Length > 0) {
      string[] fields = line.Split(',');
      ....
 }

确保跳过任何空行:

while ((line = file.ReadLine()) != null)
{
    string[] fields = line.Split(',');
    if(fields.Length == 3) //<--
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO tblUser(id, name, address) VALUES (@id, @name, @address)", con);
        cmd.Parameters.AddWithValue("@id", fields[0].ToString());
        cmd.Parameters.AddWithValue("@name", fields[1].ToString());
        cmd.Parameters.AddWithValue("@address", fields[2].ToString());
        cmd.ExecuteNonQuery();
    }
}