简体   繁体   English

二进制序列化到列表

[英]binary serialization to list

I used this information to convert a list to .txt with binary serialization. 我使用信息通过二进制序列化将列表转换为.txt。 now I want to load that file, and put it again in my list. 现在,我想加载该文件,然后再次将其放入列表中。

this is my code to convert a list to .txt with binary serialization: 这是我的代码,使用二进制序列化将列表转换为.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();
}

so my question is; 所以我的问题是 how to convert this binary file back to a list? 如何将此二进制文件转换回列表?

You can do it like this: 您可以这样做:

//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);
    }
}

Then use these methods: 然后使用以下方法:

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

Serialize(list, path);

var deserializedList = Deserialize(path);

Thanks @Hossein Narimani Rad , I used your answer and changed it a bit (so I understand it more) and now it works. 感谢@Hossein Narimani Rad,我使用了您的答案并对其进行了一些更改(因此我更加理解了),现在可以使用了。

my binair serialize method (save) is still the same. 我的binair序列化方法(保存)仍然相同。 this is my binair deserialize method (load): 这是我的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);
        }

I know I don't have an exception now, but I understand it better this way. 我知道我现在没有例外,但是通过这种方式我对此有了更好的了解。 I also added some code to fill my listbox with my List with the new LoadedList. 我还添加了一些代码,用新的LoadedList将列表填充到列表框中。

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

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