harry4713
harry4713

Reputation: 13

Read a data file into a byte array in C#

I'm trying to read a large data file containing 16-bit numbers into a multidimensional array but I'm not sure of the quickest way in C#. I also need it to work with 8-bit numbers. In C++ I used fread() which is very quick and reads the data into 'myArray[,,,,]' which can then be accessed as a multidimensional array:

numberRead = fread( myArray, sizeof(short), 19531250, stream );

In C# I could use a loop but this is very slow.

using (BinaryReader reader = new BinaryReader(File.OpenRead(filepath)))
{
  for (int i = 0; i < 25; i++)
    for (int j = 0; j < 25; j++)
      for (int k = 0; k < 25; k++)
        for (int m = 0; m < 25; m++)
          for (int n = 0; n < 25; n++)
          {
            myArray[i, j, k, m, n] = reader.ReadInt16();
          }
}

Is there a quicker way to read the file into an array which can be adapted for 8-bit and 16-bit data?

Upvotes: 1

Views: 136

Answers (1)

phuzi
phuzi

Reputation: 13079

It's slow because you're constantly asking the file system for small pieces of data. You'd be better off read the whole file in to memory in one go first 😉

using (var memStream = new MemoryStream(File.ReadAllBytes(filepath)))
using (BinaryReader reader = new BinaryReader(memStream))
{
    for (int i = 0; i < 25; i++)
        for (int j = 0; j < 25; j++)
            for (int k = 0; k < 25; k++)
                for (int m = 0; m < 25; m++)
                    for (int n = 0; n < 25; n++)
                    {
                        myArray[i, j, k, m, n] = reader.ReadInt16();
                    }
}

To read signed 8 bit integers replace reader.ReadInt16() with reader.ReadSByte();

Upvotes: 2

Related Questions