Hugo
Hugo

Reputation:

how to read and write a struct to file use C#?

I can use write(&stName,sizeof(stName),&FileName) and define a same struct in other program to read the file(XXX.h) when i use C, But I want do the same use C# and I should not use the unsafe mode. How do to solve the problem?

Edit:

thanks all. I will to try them

Edit:

Now if I want to use C write the Struct to file.h and use C# to read the struct from file.h, may I have chance solve that and not to count the offset? Because count the offset is not a good answer when I want to add some variable or other struct in the struct.

Upvotes: 2

Views: 9311

Answers (7)

Jon Skeet
Jon Skeet

Reputation: 1504122

Even in C, this is a dangerous thing to do IMO. If you use a different compiler, operating system, architecture etc you can very easily "break" your data files - you're absolutely relying on the layout of the data in memory. It's a bit like exposing fields directly instead of properties - the in-memory layout should be an implementation detail which can be changed without the public form (the file) changing.

There are lots of ways of storing data, of course. For example:

  • Binary serialization (still pretty fragile, IMO)
  • XML serialization
  • Google's Protocol Buffers
  • Thrift
  • YAML
  • Hand-written serialization/deserialization e.g. using BinaryReader and BinaryWriter

There are balances in terms of whether the file is human readable, speed, size etc. See this question for answers to a similar question about Java.

Upvotes: 2

jamesmillerio
jamesmillerio

Reputation: 3214

You can look into Google Protocol buffers as well. You may not want to add another dependency into your code, but it's meant to allow you to do this sort of thing.

Upvotes: 0

Frank Krueger
Frank Krueger

Reputation: 71063

Use Managed C++ or C++/CLI. It can read your .h file struct. It can read and write using:

read(in, &structure, sizeof(structure));
write(out, &structure, sizeof(structure));

and it can transfer that data very simply to anything else in .NET.

Upvotes: 1

Kibbee
Kibbee

Reputation: 66162

You'll have to convert each member of the struct individually using Bitconverter.convert(). This works well when your struct holds numeric data types, but you might have to do something more complex when using structs that contain more complicated data types like strings, arrays, and collections. For purposes like this, you will want to check out the .Net serialization facilities that other have mentioned.

Upvotes: 0

Arjan Einbu
Arjan Einbu

Reputation: 13692

Look at the StructLayoutAttribute

Upvotes: 1

Jason Jackson
Jason Jackson

Reputation: 17270

You should take a look at the NetDataContractSerializer. You can markup those portions of the struct that you wish to serializer and use a file stream to write them out.

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124800

Look at the ISerializable interface and Serialization in general.

Upvotes: 3

Related Questions