1

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.

2
  • This might help you BinaryFormatter.Deserialize - look at the example at the bottom.. Commented Jan 28, 2013 at 14:31
  • @Blachshma thanks, I think it could be my solution. Do you know how I can deserialize only a specific range and not the whole sequence? Commented Jan 28, 2013 at 14:36

1 Answer 1

1

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...

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but what about reading only a known range of bytes? My files are bigger than 40 GB so I can't read them to the end
BinaryFormatter receives a stream, you can play with the size, position of the stream however you like. For example, with memory-mapped files you can map a part of a large file, and access just that part of the file using a Stream.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.