views:

325

answers:

3

I want to save a struct of data in a file in C#, but I don't want to use serialize and deserialize to implement it. I want implement this action like I implement it in the C and C++ languages.

A: 

If you don't want to serialize it, you can always just use a BitConverter to convert the members to bytes via GetBytes, and write these directly to a Stream.

Reed Copsey
Ain't that pretty much the same as binary serialization?
Martinho Fernandes
I think binary serialization adds a bunch of metadata describing the type of the object which was written, as well as nested/linked objects and so forth.
Ben Voigt
For a struct, this is very minimal...
Reed Copsey
+3  A: 

System.IO - File and Streams

To implement it in the "old fashioned way" in C#/.NET, based on the assumption C++ might use raw files and streams, you need to start in the .NET Framework's System.IO namespace.

Note: This allows you complete customization over the file reading/writing process so you don't have to rely on implicit mechanisms of serialization.

Files can be managed and opened using System.IO.File and System.IO.FileInfo to access Streams. (See the inheritance hierarchy at the bottom of that page to see the different kinds of streams.)

Helper Classes

So you don't have to manipulate bits and bytes directly (unless you want to).

For binary file access you can use System.IO.BinaryReader and BinaryWriter. For example, it easily converts between native data types and stream bytes.

For text-based access file access use System.IO.StreamReader and StreamWriter. Let's you use strings and characters instead of worrying about bytes.

Random Access

If random access is supported on the stream, use a method such as Stream.Seek(..) to jump around based on on whatever algorithm you decide on for determining record lengths and such.

John K
please write more...thank you
hosseinsinohe
A: 

You can use PtrToStructure and StructureToPtr to just dump the content to/from untyped data in a byte array which you can easily push to the file as one block. Just don't try this if your structure contains references to other objects (try keeping indexes instead, perhaps).

Ben Voigt