繁体   English   中英

二进制序列化到列表

[英]binary serialization to list

我使用信息通过二进制序列化将列表转换为.txt。 现在,我想加载该文件,然后再次将其放入列表中。

这是我的代码,使用二进制序列化将列表转换为.txt:

public void Save(string fileName)
{
    FileStream fs = new FileStream(@"C:\" + fileName + ".txt", FileMode.Create);
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs, list);
    fs.Close();
}

所以我的问题是 如何将此二进制文件转换回列表?

您可以这样做:

//Serialize: pass your object to this method to serialize it
public static void Serialize(object value, string path)
{
    BinaryFormatter formatter = new BinaryFormatter();

    using (Stream fStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        formatter.Serialize(fStream, value);
    }
}

//Deserialize: Here is what you are looking for
public static object Deserialize(string path)
{
    if (!System.IO.File.Exists(path)) { throw new NotImplementedException(); }

    BinaryFormatter formatter = new BinaryFormatter();

    using (Stream fStream = File.OpenRead(path))
    {
        return formatter.Deserialize(fStream);
    }
}

然后使用以下方法:

string path = @"C:\" + fileName + ".txt";

Serialize(list, path);

var deserializedList = Deserialize(path);

感谢@Hossein Narimani Rad,我使用了您的答案并对其进行了一些更改(因此我更加理解了),现在可以使用了。

我的binair序列化方法(保存)仍然相同。 这是我的binair反序列化方法(加载):

        public void Load(string fileName)
    {
        FileStream fs2 = new FileStream(fileName, FileMode.Open);
        BinaryFormatter binformat = new BinaryFormatter();
        if (fs2.Length == 0)
        {
            MessageBox.Show("List is empty");
        }
        else
        {
            LoadedList = (List<Object>)binformat.Deserialize(fs2);
            fs2.Close();
            List.Clear();
            MessageBox.Show(Convert.ToString(LoadedList));
            List.AddRange(LoadedList);
        }

我知道我现在没有例外,但是通过这种方式我对此有了更好的了解。 我还添加了一些代码,用新的LoadedList将列表填充到列表框中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM