Click here to Skip to main content
15,308,422 members
Articles / Programming Languages / C#
Posted 10 Aug 2005


22 bookmarked

Read and Write Structures to Files with .NET

Rate me:
Please Sign up or sign in to vote.
3.66/5 (14 votes)
10 Aug 2005CPOL1 min read
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. :)


  • 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 Pin
flyboyqw7-Nov-11 14:52
Memberflyboyqw7-Nov-11 14:52 
Questiongreat work, but a clarification needed Pin
R. M. Sohail Arshed6-Nov-11 10:26
MemberR. M. Sohail Arshed6-Nov-11 10:26 
AnswerRe: great work, but a clarification needed Pin
Member 1104485612-Jan-19 0:08
MemberMember 1104485612-Jan-19 0:08 
GeneralAttempted to read or write protected memory. This is often an indication that other memory is corrupt. Pin
Reza_m_n_653-Jun-11 1:08
MemberReza_m_n_653-Jun-11 1:08 
GeneralRe: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Pin
Member 42356135-Sep-11 9:00
MemberMember 42356135-Sep-11 9:00 
QuestionError when read Struct with string Element? Pin
huynhdangthai18-May-10 17:09
Memberhuynhdangthai18-May-10 17:09 
QuestionHow to correctly write strings within a struct Pin
Tony Zackin12-Feb-10 11:03
MemberTony Zackin12-Feb-10 11:03 
GeneralWonderful! Excellent job! Pin
Graham Downs5-Jan-10 4:21
MemberGraham Downs5-Jan-10 4:21 
GeneralRe: Wonderful! Excellent job! Pin
zadeveloper.com5-Jan-10 5:22
Memberzadeveloper.com5-Jan-10 5:22 
GeneralBinarySerializer Pin
dung18-Jun-08 16:20
Memberdung18-Jun-08 16:20 
GeneralAttempted to read or write protected memory. This is often an indication that other memory is corrupt. Pin
dimas097-Mar-08 9:28
Memberdimas097-Mar-08 9:28 
QuestionHow t o write next record in a text file using the same code Pin
sajeee18-Nov-07 4:28
Membersajeee18-Nov-07 4:28 
AnswerRe: How t o write next record in a text file using the same code Pin
zadeveloper.com18-Nov-07 8:11
Memberzadeveloper.com18-Nov-07 8:11 
GeneralAutomate Write Type Pin
jasonbullard21-Jul-07 20:37
Memberjasonbullard21-Jul-07 20:37 
Questionan interesting problem Pin
teyteyi1-Jun-07 4:14
Memberteyteyi1-Jun-07 4:14 
Questionhow to write structers in Pin
laddu276-May-06 0:42
Memberladdu276-May-06 0:42 
GeneralDon't work with string Pin
leodez28-Feb-06 12:20
Memberleodez28-Feb-06 12:20 
GeneralTerrible idea Pin
Joe Woodbury11-Aug-05 8:12
professionalJoe Woodbury11-Aug-05 8:12 
GeneralRe: Terrible idea Pin
Jamie Nordmeyer11-Aug-05 9:19
MemberJamie Nordmeyer11-Aug-05 9:19 
GeneralRe: Terrible idea Pin
Joe Woodbury11-Aug-05 9:54
professionalJoe Woodbury11-Aug-05 9:54 
GeneralRe: Terrible idea Pin
Jamie Nordmeyer11-Aug-05 10:05
MemberJamie Nordmeyer11-Aug-05 10:05 
GeneralRe: Terrible idea Pin
Joe Woodbury11-Aug-05 10:15
professionalJoe Woodbury11-Aug-05 10:15 
GeneralRe: Terrible idea Pin
Jamie Nordmeyer11-Aug-05 10:16
MemberJamie Nordmeyer11-Aug-05 10:16 
GeneralRe: Terrible idea Pin
Todd Beaulieu30-Oct-06 6:11
MemberTodd Beaulieu30-Oct-06 6:11 
GeneralRe: Terrible idea Pin
Joe Woodbury30-Oct-06 6:32
professionalJoe Woodbury30-Oct-06 6:32 

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

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