首页 新闻 会员 周边

c#用Binary序列化乱码,txt文件

0
悬赏园豆:10 [已解决问题] 解决于 2019-10-29 18:15

List<Person> list = new List<Person>();
Person p = new Person();
p.ID = 1;
p.Age = 12;
p.Name = "zhiqing";
p.Money = 120.3M;
list.Add(p);
string fileName = "C:\\Users\\zhiqing\\Desktop\\test.txt";
Stream fstream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
binFormat.Serialize(fstream,list);
fstream.Close();

Console.WriteLine("c# 用二进制实现序列化");
Console.ReadLine();

 

这是源码,系列化出来乱码了,结果是这样:

   BDynamicTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null {System.Collections.Generic.List`1[[DynamicTest.Person, DynamicTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _items_size_version DynamicTest.Person[]        DynamicTest.Person   DynamicTest.Person idagenamemoney<ID>k__BackingField<Age>k__BackingField<Name>k__BackingField<Money>k__BackingField   
0  zhiqing120.3

 

求园友们帮忙一下,豆不多抱歉!

明&天的主页 明&天 | 初学一级 | 园豆:85
提问于:2015-08-28 17:00
< >
分享
最佳答案
0

能反序列化么?

收获园豆:10
Launcher | 高人七级 |园豆:45045 | 2015-08-28 17:01

每月尝试过,试试

明&天 | 园豆:85 (初学一级) | 2015-08-28 17:23

////反序列化
try
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
BinaryFormatter binayFormat = new BinaryFormatter();
List<Person> li = (List<Person>)binayFormat.Deserialize(fs);
foreach (Person per in li)
{
Console.WriteLine("反序列化结果:ID :{0}", per.ID +","+ per.Name+"," + per.Age+"," + per.Money);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
Console.WriteLine("反序列化成功");
Console.ReadLine();
}

 

测试了一下,反序列化成功了:

结果正确:

明&天 | 园豆:85 (初学一级) | 2015-08-28 17:45

@天空自由: 这说明 BinaryFormatter 的功能是正确的,微软在这个组件上并没有 BUG,至少目前还没发现。那么你“乱码”是什么意思呢?哪里有说明 BinaryFormatter 跟“乱码”的关系吗?或者说微软什么时候,在哪里声称了 BinaryFormatter 不会出现你所谓的“乱码”?

Launcher | 园豆:45045 (高人七级) | 2015-08-28 17:57

@Launcher: 明白了,只是没怎么看懂序列化的东西,最开始以为是乱码。

明&天 | 园豆:85 (初学一级) | 2015-08-28 18:17
其他回答(2)
0

你觉得应该出现什么情况???

顾晓北 | 园豆:10844 (专家六级) | 2015-08-28 17:12
1

二进制序列化,本来就是这样的。你可以考虑将其序列化为xml,json这样你就可以看懂了。

wolfy | 园豆:2636 (老鸟四级) | 2015-08-30 11:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册