Search code examples
oopbinarygeneric-list

The data changes when I try to pull it back C#


I'm trying to save a generic list and get it back by using a BinaryFormatter but I can't get the list in the form that I have saved, it returns me only the first item in the list. I think there might be an error while the code tries not to overwrite the file. If you need more details, please tell me and I'll add the details that you need.

    #region Save
    /// <summary>
    /// Saves the given object to the given path as a data in a generic list.
    /// </summary>
    protected static void Save<T>(string path, object objectToSave)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        FileStream stream;
        if (!File.Exists(path))
        {
            stream = File.Create(path);
        }
        else
        {
            stream = File.Open(path, FileMode.Open);
        }

        List<T> list = new List<T>();

        try
        {
            list = (List<T>)formatter.Deserialize(stream);
        }
        catch
        {

        }

        list.Add((T)objectToSave);

        formatter.Serialize(stream, list);
        stream.Close();
    }
    #endregion

    #region Load
    /// <summary>
    /// Loads the data from given path and returns a list of questions.
    /// </summary>
    protected static List<T> Load<T>(string path)
    {
        if (!File.Exists(path))
        {
            System.Windows.Forms.MessageBox.Show(path + " yolunda bir dosya bulunamadı!");
            return null;
        }

        BinaryFormatter formatter = new BinaryFormatter();
        FileStream stream = File.Open(path, FileMode.Open);
        List<T> newList;

        try
        {
            newList = (List<T>)formatter.Deserialize(stream);
        }
        catch
        {
            newList = null;
        }

        stream.Close();
        return newList;
    }
    #endregion

Solution

  • Okey, I just figured the problem. Appearently if you make a change in the data without saving it (I did it in "list = (List)formatter.Deserialize(stream);" this line of code) and then if you try to serialize it again, the FileStrem that you are using doesn't work generically, so you have to close the old stream and than reopen it or another again or just simply type stream = File.Open(path, FileMode.Open); again. Thanks anyway :D