Search code examples
c#unity-game-enginefilestreambinaryformatter

How to save a C# Custom Class List<> to file stream?


I want to save a custom class List (C#) in file stream (in Unity3d). I've already done saving a [Serializable] class saving into memory using this code:

[Serializable]
public class GameData
{
public int Score_SR;
public float ChaseCredits_SR;
}

Following method for saving the data:

public void Save()
{
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create(Application.persistentDataPath + "/chaserace.cr");

    // Save data here from local to orignal data path storage i.e /chaserace.cr
    GameData data = new GameData();

    data.Score_SR = Score;
    data.ChaseCredits_SR = ChaseCredits;
    // this take the "data" class data and write it to our "chaserace.cr" file
    bf.Serialize(file , data);
    file.Close();
}

And then use a method Load to load the data. But, now I would like to save a List<> of a custom class "RawData". I've tried doing the same with a List, but could not do that. Maybe there will be an edit within the code that will work for a List<>.

Here is the class whose List I want to save to memory:

[Serializable]
public class RawData{

public string key; 
public int level;  
public string value;


public RawData(string key_,string value_,int level_){
    key = key_;
    level = level_;
    value = value_;

}
}

When I try loading data, there is an Error:

BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/chaserace.cr", FileMode.Open);
RawData rawData = (RawData)bf.Deserialize(file);
List<RawData> rawDataList=rawData; //Here is conversion error
file.Close();

Solution

  • you have to Parser to a List :

    List<RawData> rawDataList = new List<RawData>() { rawData };
    

    because rawData is a single object , But you want to conversion a List

    for example :

    int a = 1;
    List<int> b = a; //Here will conversion error