索引超出了C#中数组的界限
本文关键字:数组 界限 索引 | 更新日期: 2023-09-27 17:58:29
我得到一个错误,我得到的错误是Index超出了数组的界限。
我的代码是
try
{
string path = (string)(Application.StartupPath + "''TEMP''TEMP_BACKFILL_atoz" + "''" + name_atoz);
string reader1 = System.IO.File.ReadAllText(path);
string str = reader1;
//reader1.Close();
//reader1.Dispose();
File.Delete(path);
string[] Strarray = str.Split(new char[] { Strings.ChrW(10) });
int abc = Strarray.Length - 2;
int xyz = 0;
bool status = true;
string[] strarray1 = Strarray[xyz].Split(",".ToCharArray());//the line number 3696
string SecName = strarray1[0];
string SecSym = strarray1[1];
int DT = int.Parse(strarray1[2]);
int TM = int.Parse(strarray1[3]);
float O = float.Parse(strarray1[4]);
float H = float.Parse(strarray1[5]);
float L = float.Parse(strarray1[6]);
float C = float.Parse(strarray1[7]);
double V = double.Parse(strarray1[8]);
double OI = double.Parse(strarray1[9]);
}
catch (Exception)
{
}
StackTrace表示C:''Documents and Settings''Administrator''Desktop''New Folder''Downloader''Downloadr''Downloader''Form1.cs:line 3696 中的at-Downloader.Form1.123_DoWork(Object sender,DoWorkEventArgs e)
感谢提前
string[] strarray1 = Strarray[xyz].Split(",".ToCharArray());//the line number 3696
由于这一行抛出了错误,xyz=0,因此我们必须假设strarray1此时为空。
一般来说,除非您100%确定数组包含的内容,否则在尝试访问元素之前,应始终检查其长度。
第一点:只捕获Exception对象的基类从来都不是一个好主意,尤其是对于调试来说
有时最好让visualstudio在错误点中断,然后检查变量。然后你可以检查Strarray的长度,我认为它将是0。
第二点:你有很多无用的变量,尤其是int xyz = 0;
和bool status = true;
我还想确定一下,命名变量非常有帮助,这样你以后就可以知道它们的用途了。像"O"answers"xyz"这样的名字毫无用处。
现在,对于excact问题,System.IO.File.ReadAllLines(path)
返回一个字符串数组,每行一项。您应该将string reader1 = System.IO.File.ReadAllText(path);
更改为string[] reader1 = System.IO.File.ReadAllLines(path);
然后您可以更改string[] strarray1 = Strarray[xyz].Split(",".ToCharArray());
至string[] strarray1 = reader1[0].Split(",".ToCharArray());
这应该可以解决您的问题,但您应该学习如何使用C#来正确命名变量并保持代码的整洁。一个月后,你将不知道"a"answers"xyz"是什么意思,请告诉我:-)