473,320 Members | 2,035 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

reading and writing to binary files

Hi,

I need to read/write data from/to binary files that have an already
defined.
This means I can't define classes with the [Serializable] attribute.
The files also have arrays with variable length. This means I can't use
the StructLayout attribute like in here:
http://www.builderau.com.au/architec...0277904,00.htm
I came up with my own solution using reflection. I'm just starting with
programming in the .net environment so I'm a bit unsure if this
solution is any good. Can anyone tell if there are better solutions or
if I can improve on the current solution?

class SomeStruct
{
public char[] Version =new char[8];
public int a;
public int[] b;
}

private void Write()
{
SomeStruct strct = new SomeStruct();
strct.b = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
strct.Version = "test".ToCharArray();

FileStream fs = new FileStream(@"c:\temp\test.bin", FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);

object o = WriteObject(strct, w);

w.Close();
fs.Close();
}

private void Read()
{
SomeStruct strct = new SomeStruct();
strct.b = new int[10];

FileStream fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
BinaryReader r = new BinaryReader(fs);

object o = ReadObject(strct, r);

r.Close();
fs.Close();
}

public static object ReadObject(object oObject,BinaryReader r)
{
string sFieldType;

Type tyObject = oObject.GetType();
FieldInfo[] miMembers = tyObject.GetFields();

foreach (FieldInfo info in miMembers)
{
if (info.FieldType.IsAssignableFrom(typeof(Int32)))
{
info.SetValue(oObject, r.ReadInt32());
}
else if (info.FieldType.IsAssignableFrom(typeof(Int32[])))
{
int[] tmp = (int[])info.GetValue(oObject);
int len = Buffer.ByteLength(tmp);
byte[] bts = r.ReadBytes(len);
Buffer.BlockCopy(bts, 0, tmp, 0, tmp.Length);
info.SetValue(oObject,tmp);
}
else if (info.FieldType.IsAssignableFrom(typeof(Char[])))
{
char[] tmp = (char[])info.GetValue(oObject);
tmp = r.ReadChars(tmp.Length);
info.SetValue(oObject, tmp);
}
}
return (oObject);
}

public static object WriteObject(object oObject,BinaryWriter w)
{
string sFieldType;

Type tyObject = oObject.GetType();
FieldInfo[] miMembers = tyObject.GetFields();

foreach (FieldInfo info in miMembers)
{
if (info.FieldType.IsAssignableFrom(typeof(Int32)))
{
w.Write((int)info.GetValue(oObject));
}
else if (info.FieldType.IsAssignableFrom(typeof(Int32[])))
{
int[] tmp = (int[])info.GetValue(oObject);
int len = Buffer.ByteLength( tmp );
byte[] bts= new byte[len];
Buffer.BlockCopy(tmp, 0, bts, 0, len);
w.Write(bts);
}
else if (info.FieldType.IsAssignableFrom(typeof(Char[])))
{
w.Write((char[])info.GetValue(oObject));
}
}
return (oObject);
}

Thanks,
Robert Reijntjes
Mar 16 '06 #1
2 2378
I was actuly just working on a similar problem.

I used a single function to do the reading and writing, it took a
direction parabater (store or retrive). This ment that when writing a
function to say write all feilds of a class to disk I only had to write
the code one and then change the persitance direction for a load
operation.

Anyway sf.net has a few good .NET object persistance frameworks that
are allwrite[sic].

-dm

Robert Reijntjes wrote:
Hi,

I need to read/write data from/to binary files that have an already
defined.
This means I can't define classes with the [Serializable] attribute.
The files also have arrays with variable length. This means I can't use
the StructLayout attribute like in here:
http://www.builderau.com.au/architec...0277904,00.htm
I came up with my own solution using reflection. I'm just starting with
programming in the .net environment so I'm a bit unsure if this
solution is any good. Can anyone tell if there are better solutions or
if I can improve on the current solution?

class SomeStruct
{
public char[] Version =new char[8];
public int a;
public int[] b;
}

private void Write()
{
SomeStruct strct = new SomeStruct();
strct.b = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
strct.Version = "test".ToCharArray();

FileStream fs = new FileStream(@"c:\temp\test.bin", FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);

object o = WriteObject(strct, w);

w.Close();
fs.Close();
}

private void Read()
{
SomeStruct strct = new SomeStruct();
strct.b = new int[10];

FileStream fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
BinaryReader r = new BinaryReader(fs);

object o = ReadObject(strct, r);

r.Close();
fs.Close();
}

public static object ReadObject(object oObject,BinaryReader r)
{
string sFieldType;

Type tyObject = oObject.GetType();
FieldInfo[] miMembers = tyObject.GetFields();

foreach (FieldInfo info in miMembers)
{
if (info.FieldType.IsAssignableFrom(typeof(Int32)))
{
info.SetValue(oObject, r.ReadInt32());
}
else if (info.FieldType.IsAssignableFrom(typeof(Int32[])))
{
int[] tmp = (int[])info.GetValue(oObject);
int len = Buffer.ByteLength(tmp);
byte[] bts = r.ReadBytes(len);
Buffer.BlockCopy(bts, 0, tmp, 0, tmp.Length);
info.SetValue(oObject,tmp);
}
else if (info.FieldType.IsAssignableFrom(typeof(Char[])))
{
char[] tmp = (char[])info.GetValue(oObject);
tmp = r.ReadChars(tmp.Length);
info.SetValue(oObject, tmp);
}
}
return (oObject);
}

public static object WriteObject(object oObject,BinaryWriter w)
{
string sFieldType;

Type tyObject = oObject.GetType();
FieldInfo[] miMembers = tyObject.GetFields();

foreach (FieldInfo info in miMembers)
{
if (info.FieldType.IsAssignableFrom(typeof(Int32)))
{
w.Write((int)info.GetValue(oObject));
}
else if (info.FieldType.IsAssignableFrom(typeof(Int32[])))
{
int[] tmp = (int[])info.GetValue(oObject);
int len = Buffer.ByteLength( tmp );
byte[] bts= new byte[len];
Buffer.BlockCopy(tmp, 0, bts, 0, len);
w.Write(bts);
}
else if (info.FieldType.IsAssignableFrom(typeof(Char[])))
{
w.Write((char[])info.GetValue(oObject));
}
}
return (oObject);
}

Thanks,
Robert Reijntjes


Mar 17 '06 #2
th*********@gmail.com wrote:
I was actuly just working on a similar problem.

I used a single function to do the reading and writing, it took a
direction parabater (store or retrive). This ment that when writing a
function to say write all feilds of a class to disk I only had to write
the code one and then change the persitance direction for a load
operation.

Anyway sf.net has a few good .NET object persistance frameworks that
are allwrite[sic].

-dm

The read and write functions share indeed a lot of functionality so I'll
try to turn them in to one function.

Thanks!
Mar 17 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: drife | last post by:
Hello, I need to read a Fortran binary data file in Python. The Fortran data file is organized thusly: nx,ny,nz,ilog_scale # Record 1 (Header) ihour,data3D_array # Record 2 Where...
1
by: Steve Bennett | last post by:
Can anyone suggest a good tutorial for reading and writing binary files in Perl or send me some tips or examples? I tried using pack and unpack and seek and read but things don't work as expected...
16
by: explorer | last post by:
I am learning C, so I decided to try out r/w-ing to other files. Can anyone please tell me why I get the following error when running the program? Transcript: Name? Nikhil R. Mulani Bus...
1
by: Jón Sveinsson | last post by:
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...
4
by: Owen Corpening | last post by:
Is there an equivalent way to read and write java property files in dotnet? specifically c++? fgetc just seems wrong ... owen
5
by: MichaelY | last post by:
In reference to KB article 306654 (which works perfectly otherwise), why does this method fail if the site is using SSL??? I have a series of content handlers that write non-ASP.NET files to the...
2
by: ShihChun | last post by:
Hi everyone, I encounter a problem in writing binary files for Sun Solaris system. The problem is I have an array (data type: double) need to be ported from PC to Sun Solaris workstation....
7
by: jvdb | last post by:
Hi all, I need some help on the following issue. I can't seem to solve it. I have a binary (pcl) file. In this file i want to search for specific codes (like <0C>). I have tried to solve it...
3
by: =?Utf-8?B?TWljaGFlbA==?= | last post by:
Does anyone know how I can write a binary file? Basically I want to read in a file that is an exe and write it back out bit by bit so I can add some header info. Thanks, Michael
1
by: priya mahajan | last post by:
Can anyone tell me how to write binary files at specified location on the browser???????????? for example on content pages .
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.