指数是阵列异常的边界之外 [英] Index was outside the bounds of the array exception
问题描述
下面是我的code,从平面文件中获取数据,并插入到SQL Server。它生成异常(索引是该数组的边界之外
)。
字符串路径= string.Concat(使用Server.Mappath(〜/ TempFiles中/),Fileupload1.FileName);
字符串文本= System.IO.File.ReadAllText(路径);
字符串[]行= text.Split('');
con.Open();
的SqlCommand CMD =新的SqlCommand();
字符串[]值=新的字符串[3];
的foreach(以线串线1)
{
值= line1.Split(';');
查询字符串=INSERT INTO demooo VALUES('+值[0] +','+值[1] +','+值[2] +');
CMD =新的SqlCommand(查询,CON);
cmd.ExecuteNonQuery();
}
例外情况发生,因为您的一条线路有少于三个元素用分号隔开。即使你声明值
为字符串
数组的三个元素,影响变量的结果 String.Split()
功能,使这无关紧要:您的阵列将拥有任何长度返回的数组。如果是少,你的code肯定会失败。
如果它不应该发生的,我建议你做一个断言在code帮你调试:
// ...
值= line1.Split(';');
//下面将使调试器停止执行,如果line.Length小于3
Debug.Assert的(line1.Length> = 3);
// ...
作为一个方面说明,我应该提到制作了一批插入
将更为有效。此外,您的声明和reaffecting CMD
变量是不太正确的方式。最后,你应该叫与string.replace
在你的价值观,以确保加倍的单引号。否则,你的code将是开放的SQL注入攻击。
Here is my code to get data from a flat file and insert into SQL Server. It is generating an exception (Index was outside the bounds of the array
).
string path = string.Concat(Server.MapPath("~/TempFiles/"), Fileupload1.FileName);
string text = System.IO.File.ReadAllText(path);
string[] lines = text.Split(' ');
con.Open();
SqlCommand cmd = new SqlCommand();
string[] Values = new string[3];
foreach (string line1 in lines)
{
Values = line1.Split(';');
string query = "INSERT INTO demooo VALUES ('" + Values[0] + "','" + Values[1] + "','" + Values[2] + "')";
cmd = new SqlCommand(query,con);
cmd.ExecuteNonQuery();
}
The exception happens because one of your lines has less than three elements separated with a semicolon. Even though you declare Values
as a String
array of three elements, affecting the variable to the result of String.Split()
function makes that irrelevant: your array will have whatever length the returned array has. If it's less, your code will definitely fail.
If it's not supposed to happen I suggest you do an assertion in your code to help you debugging:
// ...
Values = line1.Split(';');
// the following will make the debugger stop execution if line.Length is smaller than 3
Debug.Assert(line1.Length >= 3);
// ...
As a side note, I should mention making a batch INSERT
would be far more efficient. Also your way of declaring and reaffecting cmd
variable isn't quite correct. And finally you should call String.Replace
on your values to make sure any apostrophes is doubled. Otherwise your code will be open for SQL injection attacks.
这篇关于指数是阵列异常的边界之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!