Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从自定义(模板)数组中的文件读取字节_C#_.net_Readfile - Fatal编程技术网

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

C# 从自定义(模板)数组中的文件读取字节,c#,.net,readfile,C#,.net,Readfile,我有一个二进制文件。一段数据可以是8,16,32,64位有符号和无符号整数。我正在尝试编写模板函数,以下是我迄今为止所做的工作: public T[] GetLayerBytes<T>(int LayerNum) { int typeSize = Marshal.SizeOf(typeof(T)); int layerPixelCount = typeSize * bitmapWidth * bitmapHeigth;

我有一个二进制文件。一段数据可以是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;
        }
    }
public T[]GetLayerBytes(intlayernum)
{
int typeSize=Marshal.SizeOf(typeof(T));
int layerPixelCount=字体大小*位图宽度*位图高度;
string recFileName=“my.rec”;
使用(FileStream fs=File.OpenRead(recFileName))
使用(BinaryReader br=新的BinaryReader(fs))
{
Seek(layerPixelCount*LayerNum,SeekOrigin.Begin);
T[]b=新的T[layerPixelCount];
//读取(b,0,layerPixelCount);这不起作用
//读取(b,0,layerPixelCount);这也不起作用
返回b;
}
}
< C++ >我会用到这个。

对于不同的
T
类型,是否有任何方法可以读取字节/int16/uint16等,类似于我在没有开关/case的情况下尝试的方法


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

根据您的意见,我建议使用该方法

BinaryFormatter有一个属性,可用于选择所需对象的类型


此外,我认为您需要使用,以便以您想要的方式转换序列化数据

根据您的评论,我建议使用这种方法

BinaryFormatter有一个属性,可用于选择所需对象的类型


此外,我认为您需要使用,以便以您想要的方式转换序列化数据

这可能会对你有所帮助-看看下面的例子。@Blachshma谢谢,我认为这可能是我的解决方案。你知道我如何只反序列化一个特定的范围而不是整个序列吗?这可能会帮助你-看看下面的例子。@Blachshma谢谢,我想这可能是我的解决方案。你知道我如何只反序列化一个特定的范围而不是整个序列吗?谢谢,但是只读取一个已知的字节范围怎么样?我的文件大于40GB,因此我无法将其读取到endBinaryFormatter接收到流时,您可以随意调整流的大小和位置。例如,使用,您可以映射大文件的一部分,并使用流仅访问该部分文件。谢谢,但是只读取已知范围的字节怎么样?我的文件大于40GB,因此我无法将其读取到endBinaryFormatter接收到流时,您可以随意调整流的大小和位置。例如,使用可以映射大文件的一部分,并使用流仅访问该部分文件。