Search code examples
c#memory.net-micro-frameworknetduino

.NET Micro Framework, reading files on a device with limited memory


On a ChipworkX device we would read files using:

File.ReadAllBytes(filename);

But if we try that on a NetDuino Plus which has a much smaller amount of memory,
we simply get an OutOfMemoryException.

The files are not that big, but I guess that's all relative in this case (1.5kb max).

What's the correct way to read files on a device like this?


Solution

  • Use a FileStream

    using (var fileStream = new FileStream(filename, FileMode.Open))
    {
        byte[] block = new byte[1024];
        int readLength;
        while ((readLength = fileStream.Read(block, 0, block.Length)) > 0)
        {
            Process(block, readLength);
        }
    }
    

    write your own Process method. The block length of 1024 is just an example, read as big chunks as you can process at a time. You can vary that depending on the data.