Reading through binary files

  • Thread starter =?iso-8859-1?Q?J=F3n_Sveinsson?=
  • Start date
?

=?iso-8859-1?Q?J=F3n_Sveinsson?=

Hello everyone

I have been able to read data from binary files to
filestrean, the data in the files are structured, what
I'm trying to do is to loop through the binary files and
add data to my struct, in this file there are lot of
records i need to loop trough, first time I read the
file, the data is fine but for the rest the data is not
correct
here is my code for reading the binary files and loop
through the code, what is wrong with the code

public static void Main()
{
PRD_record rec = new PRD_record();//struct which
has been written to file

FileStream fs = new FileStream
(@"c:\elas.dat",FileMode.Open);//Filestream to read text
TextWriter tw = new StreamWriter
(@"c:\elas.txt");//Textwriter to write out text

byte[] array = new byte[Marshal.SizeOf(rec)];

while((fs.Read(array,0,Marshal.SizeOf(rec))!=0))
{
rec = BytesToYourStruct(array);
tw.WriteLine(rec.abs_pot_no + " " + rec.md.Blev);

}

fs.Close();
tw.Close();

}


//Converting my structure to bytes
static byte[] YourStructToBytes( PRD_record s )
{

int size = Marshal.SizeOf( s );
byte[] retArr = new byte[ size ];
IntPtr buf = Marshal.AllocHGlobal( size ); // create
unmanaged memory
Marshal.StructureToPtr ( s, buf, false ); // copy
struct

for (int i=0; i<size; ++i)
{
retArr = Marshal.ReadByte(buf, i); // read
unmanaged bytes
}
Marshal.FreeHGlobal( buf );
return retArr;
}



//Converting my bytes to struct
static PRD_record BytesToYourStruct( byte[] arr )
{

PRD_record s;
IntPtr arrayPointer=Marshal.UnsafeAddrOfPinnedArrayElement
(arr,0);
s=(PRD_record)Marshal.PtrToStructure(arrayPointer,typeof
(PRD_record));
return s;

}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top