Convert structure to bytes and writing it to a file

Many time we may require to write the data of structure in file in the form of bytes. So consider the structure written below:


[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct student
        {
            [MarshalAs(UnmanagedType.LPWStr,SizeConst=10)]
            public string Name;
            [MarshalAs(UnmanagedType.I4)]
            public int RollNo;
            [MarshalAs(UnmanagedType.I4)]
            public int Marks;
        }

Many I am considering that you know How to convert structure into IntPtr (Click here to know how to convert Structure into IntPtr). So I will write that code directly in Example.

Consider ptrStudent, a IntPtr pointer which is pointing to the unmanaged memory which is containing structure in sequential layout.

Code for getting IntPtr of object of student

st: object of student

IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
Marshal.StructureToPtr(st, ptrStudent, true);

Now we have to get byte[] from IntPtr (ptrStudent).



To get byte[] from IntPtr, we have a static method "Copy" of System.Runtime.InteropServices.Marshal class.

         Signature of Method
            public static void Copy(object structure, IntPtr ptr, bool bDeleteOld)

Code to Get Byte Array of Structure:



byte[] val = new byte[Marshal.SizeOf(typeof(student))];
Marshal.Copy(ptrStudent, val, 0, val.Length);

Now, byte[] val contains the structure in the form of bytes

Write the byte[] in File:

To perform operation on file, in dot net we have provided FileStream class. To write the byte[] in file, there is a method which is 
public void Write(byte[] data, int offSet, int length);

Code

//Creating the object of File Stream and opening / creating the file in write mode
FileStream fs = new FileStream("Student.txt", FileMode.OpenOrCreate, FileAccess.Write);
//Writing byte array
fs.Write(val, 0, val.Length);
//Closing the file stream
fs.Close();

Complete Code for writing the Structure in File in form of bytes


public void WriteStructureInFile()
        {
            student st = new student();
            st.Name = "Akash Soni";
            st.RollNo = 483;
            st.Marks = 807;
            IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
            Marshal.StructureToPtr(st, ptrStudent, true);
            byte[] val = new byte[Marshal.SizeOf(typeof(student))];
            Marshal.Copy(ptrStudent, val, 0, val.Length);
 //Creating the object of File Stream and opening / creating the file in write mode
    FileStream fs = new FileStream("Student.txt",FileMode.OpenOrCreate, FileAccess.Write);
            //Writing byte array
          fs.Write(val, 0, val.Length);
            //Closing the file stream
          fs.Close();
            Marshal.FreeHGlobal(ptrStudent);//Freeing the allocated memory
        }

Output