Search code examples
c#slimdxjoystick

Save joystick list


How can I save and load List of SlimDX.DirectInput.Joystick to/from a file? I tried

using (Stream stream = File.Open("joys.xml", FileMode.Create))
{
    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

    bformatter.Serialize(stream, usedsticks);
}

but I got an exception:

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll

Additional information: Typ SlimDX.DirectInput.Joystick v sestavení SlimDX, Version=4.0.13.43, Culture=neutral, PublicKeyToken=b1b0c32fd1ffe4f9 není označen jako serializovatelný.


Solution

  • I don't speak Czech, but I suppose "Typ SlimDX.DirectInput.Joystick není označen jako serializovatelný." means "type SlimDX.DirectInput.Joystick isn't serializable". That means that SlimDX.DirectInput.Joystick simply cannot be instantiated via deserialization.

    The object class you are trying to serialize must be marked as serializable. See the relevant question about the SerializableAttribute class - What is [Serializable] and when should I use it?

    Considering the original problem, normally you're supposed to write your own serializable classes for saving. You should instantiate SlimDX.DirectInput.Joystick (or any) objects in a usual way using loaded data afterwards.

    In order to save your object into a file you could choose a suitable file format. For instance, JSON - Turn C# object into a JSON string in .NET 4