【问题标题】:binary serialization to list二进制序列化到列表
【发布时间】:2015-04-03 16:42:21
【问题描述】:
我使用this 信息将列表转换为带有二进制序列化的.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();
}
所以我的问题是;如何将此二进制文件转换回列表?
【问题讨论】:
标签:
c#
list
serialization
【解决方案1】:
你可以这样做:
//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);
【解决方案2】:
感谢@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 填充列表框。