Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a custom type as binary data in .NET?

I'm creating something that has save files. For the most part, it's just saving objects with 4 values.

  • x
  • y
  • id
  • layer

I've been saving this as XML for a while, the problem is, the files are starting to get HUGE because I'm saving hundreds to thousands of these objects and XML is kind of bulky for something like this. I tried switching to Json but it was too big as well (I will admit though, better).

My Question

I know a lot of programs save directly using bytes to conserve space. I want to do this. Say I have 300 objects with the properties X, Y, Id, and Layer, how could I save this to file x as bytes and load it later?

I've tried reading bytes when I used to make my own servers. I usually ended up getting frustrated and giving up. I'm hoping this isn't too similar (my gut says otherwise).

EDIT

Oh sorry guys, I forgot to mention, I'm using VB.NET so all .NET answers are acceptable! :)

Also, all of these values are integers.

like image 702
Freesnöw Avatar asked Feb 23 '23 21:02

Freesnöw


2 Answers

I would use protobuf-net (I would; I'm biased...). It is an open-source .NET serializer, that uses attributes (well, that is optional in v2) to guide it. For example, using C# syntax (purely for my convenience - the engine doesn't care what language you use):

[ProtoContract]
public class Whatever {
    [ProtoMember(1)]
    public int X {get;set;}
    [ProtoMember(2)]
    public int Y {get;set;}
    [ProtoMember(3)]
    public long Id {get;set;}
    [ProtoMember(4)]
    public string Layer {get;set;}
}

You can then serialize, for example:

List<Whatever> data = ...
Serializer.Serialize(file, data);

and deserialize:

var data = Serializer.Deserialize<List<Whatever>>(file);

job done; fast binary output. You probably can get a little tighter by hand-coding all reading/writing manually without any markers etc, but the above will be a lot less maintenane. It'll also be easy to load into any other platform that has a "protocol buffers" implementation available (which is: most of them).

like image 98
Marc Gravell Avatar answered Mar 04 '23 07:03

Marc Gravell


Alternative: why not xml and zip (or some other compression)

Advantage:
* its still "human" readable
* text files have normaly a good compression factor

Also what programming languae you are using? in C/C++ or you create a struct with the data reinterpret cast the struct to byte * and write sizeof bytes to the file... simple as that (assuming the struct is fixed size (id and layer are also fixed sized variables like int)

like image 22
nobs Avatar answered Mar 04 '23 08:03

nobs