2015-04-03 97 views
2

我用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(); 
} 

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

+0

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 – 2015-04-03 17:17:40

回答

0

你可以这样说:

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

感谢@Hossein Narimani RAD,我用你的答案,并改变了一点(所以我的理解更多),现在它工作。

我的binair序列化方法(保存)仍然是一样的。 这是我binair Deserialize方法(负载):

 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。