VladL
VladL

Reputation: 13033

read bytes from file in custom (template) array

I have a binary file. One piece of data can be 8,16,32,64 bit signed and unsigned int. I'm trying to write the template function and here is what I've done until now:

    public T[] GetLayerBytes<T>(int LayerNum)
    {
        int typeSize = Marshal.SizeOf(typeof(T));

        int layerPixelCount = typeSize * bitmapWidth * bitmapHeigth;

        string recFileName = "my.rec";

        using (FileStream fs = File.OpenRead(recFileName))
        using (BinaryReader br = new BinaryReader(fs))
        {
            fs.Seek(layerPixelCount * LayerNum, SeekOrigin.Begin);
            T[] b = new T[layerPixelCount];

            //fs.Read(b, 0, layerPixelCount); this doesn't work
            //br.Read(b, 0, layerPixelCount); this doesn't work too
            return b;
        }
    }

In C++ I would use CFile::Read for this.

Is there any way to read bytes/int16/uint16 etc. similar to what I've tried without switch/cases for different T types?

Thanks in advance for all possible ellegant solutions.

Upvotes: 1

Views: 219

Answers (1)

Blachshma
Blachshma

Reputation: 17395

Based on your comments, I'd recommend using the BinaryFormatter.Deserialize method.

The BinaryFormatter has a Binder property which you can use for choosing the type of the object you want.

In addition, I think you'll want to use the SurrogateSelector in order to transform the serialized data however you want...

Upvotes: 1

Related Questions