Search code examples
c#arraysfilestream

how to resolve : index out of bound C# arrays, streams


i get index out of bound on line : stream.Read(fileBytes[i], 0, fileBytes[i].Length); any help would be appreciated . thanks :)

string[] path = new string[15];
byte[][] fileBytes = new byte[10][];
for (int i = 1; i <= 10; i++) {

 path[i] = @ "C:\Users\t-chkum\Desktop\InputFiles\1MB\" + i + ".txt ";

 // readind data/* 
 FileStream stream = File.OpenRead(path[i]);
 fileBytes[i] = new byte[stream.Length];

 //  Console.WriteLine(stream.Length);
 stream.Read(fileBytes[i], 0, fileBytes[i].Length);
 stream.Close();
}

Solution

  • You are iterating from i=1 to 10 inclusive. But, the size of the array is 10 i.e. the index goes from 0 to 9. So, either start i from 0, or index using i-1. Also, use try-catch. This would help you to debug better.

    Otherwise, the code is working fine for me.