日期:2014-05-18 浏览次数:20843 次
public void bReadFile(string file, ListBox lb) { using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { BinaryReader br = new BinaryReader(fs); char[] car = br.ReadChars((int)fs.Length); string[] scar = OutPutArray(car); lb.Items.AddRange(scar);//把文件读入到ListBox里面 br.Close(); } } public string[] OutPutArray(char[] car) { string[] ss = {};//这行错误吗? 有位同学将其赋值为null没事,而我会报“没有new”的错误 //string ss2 = ""; int k = 0; for (int i = 0; i <= car.Length; i++) { //MessageBox.Show(car.Length.ToString()); while (car[i] != ',' && i != car.Length) { ss[k] += car[i];//这行代码出现“索引超出了数组界限”,想不明白 i++; } //ss[k] = ss2; k++; //ss2 = ""; //i++; } return ss; }
public void bReadFile(string file, ListBox lb) { using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { BinaryReader br = new BinaryReader(fs); char[] car = br.ReadChars((int)fs.Length); string[] scar = OutPutArray(car); lb.Items.AddRange(scar); br.Close(); } } public string[] OutPutArray(char[] car) { int len = 0; //存储要分配的字符数组的个数 for (int i = 0; i < car.Length; i++) { if (car[i] != ',') { len++; } } int k = 0; string[] ss=new string[len]; //必须要new了才能分配内存空间 for (int i = 0; i < car.Length; i++) { //这个里面不要套while了,外面那层for已经是循环了 if (car[i] != ',') //&& i != car.Length这个也已经通过 for里面的i < car.Length实现了。 { ss[k] += car[i]; k++; } } return ss; }
------解决方案--------------------
public void bReadFile(string file, ListBox lb) { using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { BinaryReader br = new BinaryReader(fs); string[] scar = br.ReadString().Split(new char[] { ',' }); lb.Items.AddRange(scar);//把文件读入到ListBox里面 br.Close(); } }