Allows you to serialize and deserialize objects who's size is known to and from a byte array representing the data structure in binary.
Note
This library only supports primitive value types1 and other value types2 on top of arrays of these types.
This has to do with this library mapping the data directly to binary. Reference types are dynamic by nature, so storing these in binary will need another approach.34
- Follow the steps here.
- Search the package namespace seen above.
- Select the package
- Select the version you'd like to install
- Run the command listed above in the directory of the project you wish to install the package in.
Method | Explanation |
---|---|
byte[] BinarySerializer .Serialize <T >(T obj) |
serializes the object into it's binary representation to the buffer which is returned. |
void BinarySerializer .Deserialize <T >(byte[] buf) |
deserializes T from the specified buffer at buf . |
In C#, you can use the built-in functions defined in File
;
byte[] data = File.ReadAllBytes("./some/filepath.bin"); // reading the data stored at the path
File.WriteAllBytes("/tmp/dontdelete.bin", data); // writing to the binary file
If you don't want to serialize some fields, you can utilise the built-in NonSerialized
attribute
Footnotes
-
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in- ↩
-
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types ↩
-
This has been done with arrays, as they are reference types in C#. So 4 extra bytes are allocated per array to specify it's Length. ↩
-
If this is the kind of behaviour you are looking for, consider using a library like
Newtonsoft.Json
(orNewtonsoft.Json.Bson
for binary-json). ↩