API SaveTypeWriterReader - shmellyorc/Box GitHub Wiki
Namespace: Box.Saves
An abstract base class that handles serialization and deserialization of objects of type T
to and from binary files, with optional compression. When saving, data is written via SaveContentWriter
and compressed only if the compressed data is smaller than the raw form; when loading, the file is auto-detected for compression, decompressed if needed, and then read via SaveContentReader
. Throws a FileNotFoundException
if the save file does not exist.
protected SaveTypeWriterReader()
Creates a new instance of the SaveTypeWriterReader<T>
base class. Since this class is abstract, this constructor is invoked by derived implementations to set up any necessary base state.
Method Signature | Description | Returns |
---|---|---|
T Load(string filename) |
Loads an object of type T from the specified file. Throws a FileNotFoundException if the file does not exist. Automatically handles optional decompression. |
T |
void Save(string filename, T data) |
Saves the specified object of type T to the given file path. Data is compressed only if compression yields a smaller size; otherwise, raw data is saved. |
void |
protected abstract void Save(SaveContentWriter writer, T value) |
When implemented in a derived class, writes the object data into the provided SaveContentWriter . |
void |
protected abstract T Load(SaveContentReader reader) |
When implemented in a derived class, reads and reconstructs the object data from the provided SaveContentReader . |
T |
// Define a data type to save
public class PlayerData
{
public int Level { get; set; }
public string Name { get; set; }
}
// Implement a concrete handler
public class PlayerDataHandler : SaveTypeWriterReader<PlayerData>
{
protected override void Save(SaveContentWriter writer, PlayerData value)
{
writer.Write(value.Level);
writer.Write(value.Name);
}
protected override PlayerData Load(SaveContentReader reader)
{
int level = reader.ReadInt();
string name = reader.ReadString();
return new PlayerData { Level = level, Name = name };
}
}
// Usage
var handler = new PlayerDataHandler();
var player = new PlayerData { Level = 5, Name = "Avery" };
// Save (auto-compress if beneficial)
handler.Save("save1.bin", player);
// Load (auto-decompress if needed)
PlayerData loaded = handler.Load("save1.bin");
Console.WriteLine($"Level: {loaded.Level}, Name: {loaded.Name}");