using (var br = new BinaryReader(File.Open("bw.bin", FileMode.Open, FileAccess.Read), Encoding.ASCII)) { Numr = br.ReadInt32(); //количество записей, первая строка в файле for (int i = 0; i < Numr; i++) { StArray[i].Mark = br.ReadString(); //в строке вылетает исключение "Index out of range" StArray[i].Year = br.ReadInt32(); StArray[i].Volume = (float) br.ReadDouble(); StArray[i].Mileage = br.ReadInt32(); } } 
  • You did not apparently create an array of StArray, or its size is smaller than the number of rows. - Dmitry Polyanin
  • The array is created, before it is used many times and very successfully, its size is fixed - the number of elements whose value increases when an element is added to the array and decreases when it is deleted, the binary file that is being written is an array of structures, the first line is the number of elements 4 records follow - ivas1ly
  • Such errors are corrected by the programmer himself using debugging. Put a breakpoint on the for(..) and check the status of the StArray array. - Bulson 5:41 pm
  • first line in the file - do you have exactly a binary file? ReadInt32 reads the first four bytes , not the first line. If you have the number of elements written in the first line, the text - it is worth reading the file as a text. - PashaPash

1 answer 1

Index out of range means that you are trying to access an array element that does not exist that is greater than the maximum index.

That is, the size of your array is less than the number of iterations of your loop.

A debugger is best suited for debugging such things. Put a breakpoint on the line on which the error falls and study.

In your case, see the current i , and the total length of the array.

 Numr = br.ReadInt32(); 

This is not a very good approach to writing a file (not in all situations but most often), because for some reason (perhaps you have it) there may be a number that does not correspond to the real number of elements.

Look towards the solution to read before reaching the end of the file.