Reading binary files

  • Thread starter Thread starter Manjunath sp via DotNetMonster.com
  • Start date Start date
M

Manjunath sp via DotNetMonster.com

Hi,
How to effectively write and read structures from binary files in .Net?
Currently I am using functions like ReadInt32 and the likes to read
data from binary file into each elements of a structure, but this is very
inefficent compared to VB3 where I could use Get method to read the whole
structure data? Is there any similar method in .net?
 
Have you looked at using serialization? Here's quick example:

[Serializable]
struct MyStruct
{
public int anInt;
public byte aByte;
}

static void Main(string[] args)
{
MyStruct s1;
s1.anInt = int.MaxValue;
s1.aByte = byte.MaxValue;

Stream stream = File.Open(@"c:\test.bin", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, s1);
stream.Close();

stream = File.Open(@"c:\test.bin", FileMode.Open);

MyStruct s2 = (MyStruct)formatter.Deserialize(stream);

Console.WriteLine("anInt = {0}\naByte = {1}", s2.anInt, s2.aByte);
}

Check out
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfsystemserializableattributeclasstopic.asp for more info on the
SerializableAttribute class.

hth

-Joel
--------------------
From: "Manjunath sp via DotNetMonster.com" <[email protected]>
Subject: Reading binary files
Date: Fri, 22 Apr 2005 11:59:50 GMT
Organization: http://www.DotNetMonster.com
Message-ID: <[email protected]>
X-Abuse-Report: http://www.DotNetMonster.com/Uwe/NB/Abuse.aspx
Newsgroups: microsoft.public.dotnet.languages.csharp
NNTP-Posting-Host: mail.advenet.com 216.32.72.34
Lines: 1
Path: TK2MSFTNGXA01.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNGP10.phx.gbl
Xref: TK2MSFTNGXA01.phx.gbl microsoft.public.dotnet.languages.csharp:93661
X-Tomcat-NG: microsoft.public.dotnet.languages.csharp

Hi,
How to effectively write and read structures from binary files in .Net?
Currently I am using functions like ReadInt32 and the likes to read
data from binary file into each elements of a structure, but this is very
inefficent compared to VB3 where I could use Get method to read the whole
structure data? Is there any similar method in .net?

This reply is provided AS IS, without warranty (express or implied).
 
Back
Top