Reading large files with XNA on the Xbox 360

by thomas 20. July 2011 10:33

In my Game Engine, I have a Resource Manager that handle the loading of big data files asynchronously. Everything was working correctly on my PC but when I tried my code on the Xbox 360, the internal byte array of my resource was not completely filled. (A lot of bytes were equals to 0)

The problem was due to the fact that I didn’t use the Stream.Read method correctly. The third parameter is not here to pass the number of bytes to read but to specify the maximum bytes to read.

On the PC, Windows has a large buffer enough to read files larger than 100 MB in one time but on the Xbox 360 this is not the case. It can only read 20 MB at one time.

Next time, I will read the documentation more carefully, thanks to the Xbox 360 I was able to catch that bug. Sourire

Here is the correct way to read a big file into a byte array:

using (Stream stream = storage.OpenStream(path))
{
   resourceData = new byte[stream.Length];

   var remainingBytesCount = (int)stream.Length;
   var offset = 0;

   while (remainingBytesCount > 0)
   {
       var readedBytesCount = stream.Read(resourceData, offset, remainingBytesCount);

       if (readedBytesCount == 0)
       {
           break;
       }

       offset += readedBytesCount;
       remainingBytesCount -= readedBytesCount;
    }
}

Resources:

http://msdn.microsoft.com/en-us/library/system.io.stream.read(d=lightweight).aspx

Tags:

Pingbacks and trackbacks (1)+

Month List