当我尝试将其拉回C#时,数据发生了变化

时间:2018-06-27 17:24:18

标签: oop binary generic-list

我试图保存一个通用列表,并使用BinaryFormatter取回,但是我无法以保存的形式获得列表,它仅返回列表中的第一项。我认为代码尝试不覆盖文件时可能会出现错误。如果您需要更多详细信息,请告诉我,我会添加您需要的详细信息。

    #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

1 个答案:

答案 0 :(得分:0)

Okey,我刚刚发现了问题。显然,如果您在不保存数据的情况下进行了更改(我在“ list =(List)formatter.Deserialize(stream);”这一行代码中完成了此操作),然后如果尝试再次对其进行序列化,则FileStrem不能正常使用,因此您必须关闭旧流,然后重新打开它或再次打开它,或者只需键入stream = File.Open(path,FileMode.Open);再次。还是谢谢你:D