Read Struct out of a file with BinaryReader : Binary Read Write « File Stream « C# / C Sharp






Read Struct out of a file with BinaryReader

     


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;


public static class Helper
{

    public static T ReadStruct<T>(BinaryReader binary_reader) where T : struct
    {
        Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
        binary_reader.Read(buffer, 0, buffer.Count());

        GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

        T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        handle.Free();
        return result;
    }


}

   
    
    
    
    
  








Related examples in the same category

1.Binary Writer Reader
2.new BinaryReader(stream)
3.StreamWriter and BinaryWriter
4.new BinaryWriter(stream) and Write method
5.Creating a sequential-access file
6.Reading a sequential-access fileReading a sequential-access file
7.BinaryWriter and BinaryReader classes for the writing and reading of primitive typesBinaryWriter and BinaryReader classes for the writing and reading of primitive types
8.Working with the BinaryWriter Class
9.Working with the BinaryReader ClassWorking with the BinaryReader Class
10.File pointer move and read binary file
11.Write and then read back binary dataWrite and then read back binary data
12.Use BinaryReader and BinaryWriter to implement a simple inventory programUse BinaryReader and BinaryWriter to implement 
   a simple inventory program
13.Read the data from a file and desiralize it
14.Read and Write a Binary File
15.extends BinaryReader
16.Write a value at a given position. Used to write a size of data in an earlier located header.