Click here to Skip to main content
Click here to Skip to main content

Read and Write Structures to Files with .NET

, 10 Aug 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
Reading and writing structure data to and from Binary files
Sample Image - readwritestructstobinfile.jpg


I have always found that when transporting data via files, one of the best methods is to store that data into a structure and then read it out in that structure again. Two of the main reasons for this would be: No one can read the data out the files without the structure and if you are transporting that data via TCP/IP, the traffic is reduced as the files are "compressed".

You could even use a binary file as a very simple data store when you have a small task to perform and do not want to transport your application with a database.


The source file is basically one class which you can plug and play into any project.

The Constructor

The constructor of the class accepts the file name and a type. This is the struct type. i.e.: If you had a struct:

public struct MyStruct 
    public int i; 
    public string sz; 

Then the type passed into the constructor would be the type of the struct, i.e.:

StructFile structfile = new StructFile(@"c:\test.dat", typeof(MyStruct)); 
public StructFile(string szFile, System.Type type) 
    _File = szFile; 
    _oType = type; 

To use the class after it has been initialized, you need to call Open to open the files. This is a wrapper for the FileStream object and accepts the same parameters.

As the class had to be generic enough to cater to all structures, it is internally an object type.

Writing the Struct to the File

public bool WriteStructure(object oStruct) 
    _oStruct = oStruct; 
        byte[] buf = StructToByteArray(); 
        BinaryWriter bw = new BinaryWriter(_fs); 
        bw = null; 
        return true; 
    catch (Exception ex) 
        throw ex; 

private byte[] StructToByteArray() 
        // This function copies the structure data into a byte[] 

        //Set the buffer to the correct size 
        byte[] buffer = new byte[Marshal.SizeOf(_oStruct)]; 

        //Allocate the buffer to memory and pin it so that GC cannot use the 
        //space (Disable GC) 
        GCHandle h = GCHandle.Alloc(buffer , GCHandleType.Pinned); 

        // copy the struct into int byte[] mem alloc 
        Marshal.StructureToPtr(_oStruct, h.AddrOfPinnedObject(), false); 

        h.Free(); //Allow GC to do its job 

        return buffer; // return the byte[]. After all that's why we are here 
                       // right. 
    catch (Exception ex) 
        throw ex; 

The structure is passed into the WriteStructure function as an object. The object is then converted to a byte[] which binarywriter can use to print the data.

Reading the Data Back

public object GetNextStructureValue() 
    byte[] buffer = new byte [Marshal.SizeOf(_oType)]; 

    object oReturn = null; 
        if (EOF) return null; 
        _fs.Read(buffer, 0, buffer.Length); 
        GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); 
        oReturn = (object)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),
        if (_fs.Position >= _fs.Length) 
        return oReturn; 
    catch (Exception ex) 
        throw ex; 

Always remember to close the file once you are finished with it. Smile | :)


  • 10th August, 2005: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author
Architect Unitrade
South Africa South Africa
Born Jarrod Pereira in 1981
Finished School in 1999
Developer ever since Smile | :)
Happy coding.
All things are possible through Christ who strengthens me.

Comments and Discussions

QuestionCrashes when using arrays Pinmemberflyboyqw7-Nov-11 15:52 
Questiongreat work, but a clarification needed Pinmemberrmsohaila6-Nov-11 11:26 
GeneralAttempted to read or write protected memory. This is often an indication that other memory is corrupt. PinmemberReza_m_n_653-Jun-11 2:08 
GeneralRe: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. PinmemberMember 42356135-Sep-11 10:00 
QuestionError when read Struct with string Element? Pinmemberhuynhdangthai18-May-10 18:09 
QuestionHow to correctly write strings within a struct PinmemberTony Zackin12-Feb-10 12:03 
GeneralWonderful! Excellent job! PinmemberGraham Downs5-Jan-10 5:21 
GeneralRe: Wonderful! Excellent job! PinmemberJarrodPereira5-Jan-10 6:22 
GeneralBinarySerializer Pinmemberdung18-Jun-08 17:20 
GeneralAttempted to read or write protected memory. This is often an indication that other memory is corrupt. Pinmemberdimas097-Mar-08 10:28 
QuestionHow t o write next record in a text file using the same code Pinmembersajeee18-Nov-07 5:28 
AnswerRe: How t o write next record in a text file using the same code PinmemberJarrodPereira18-Nov-07 9:11 
GeneralAutomate Write Type Pinmemberjasonbullard21-Jul-07 21:37 
Questionan interesting problem Pinmemberteyteyi1-Jun-07 5:14 
Questionhow to write structers in Pinmemberladdu276-May-06 1:42 
GeneralDon't work with string Pinmemberleodez28-Feb-06 13:20 
GeneralTerrible idea PinmemberJoe Woodbury11-Aug-05 9:12 
GeneralRe: Terrible idea PinmemberJamie Nordmeyer11-Aug-05 10:19 
GeneralRe: Terrible idea PinmemberJoe Woodbury11-Aug-05 10:54 
GeneralRe: Terrible idea PinmemberJamie Nordmeyer11-Aug-05 11:05 
GeneralRe: Terrible idea PinmemberJoe Woodbury11-Aug-05 11:15 
GeneralRe: Terrible idea PinmemberJamie Nordmeyer11-Aug-05 11:16 
GeneralRe: Terrible idea PinmemberTodd Beaulieu30-Oct-06 7:11 
GeneralRe: Terrible idea PinmemberJoe Woodbury30-Oct-06 7:32 
GeneralRe: Terrible idea Pinmemberseejay112023-Mar-10 7:36 
GeneralWhat's the difference-- PinmemberdzCepheus11-Aug-05 8:32 
GeneralGreat work PinmemberThomas Lykke Petersen10-Aug-05 21:47 
GeneralRe: Great work Pinmemberkornman0012-Aug-05 13:50 
GeneralA much easier way Pinmemberleppie10-Aug-05 8:12 
GeneralRe: A much easier way PinmemberHumanOsc11-Aug-05 4:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 10 Aug 2005
Article Copyright 2005 by
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid