从自定义(模板)数组中的文件读取字节

时间:2013-01-28 13:51:24

标签: c# .net readfile

我有一个二进制文件。一个数据可以是8,16,32,64位有符号和无符号整数。我正在尝试编写模板函数,这是我迄今为止所做的:

    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;
        }
    }

在C ++中,我会使用CFile::Read来实现此目的。

是否有任何方法可以读取bytes / int16 / uint16等,类似于我在不使用T类型的切换/案例的情况下尝试的内容?

提前感谢所有可能的优雅解决方案。

1 个答案:

答案 0 :(得分:1)

根据您的评论,我建议您使用BinaryFormatter.Deserialize方法。

BinaryFormatter具有 Binder 属性,您可以使用该属性选择所需对象的类型。

此外,我认为您希望使用 SurrogateSelector 转换序列化数据,但是您想要...