在學(xué)習(xí)序列化的時(shí)候出現(xiàn)一個(gè)問題
protected void Unnamed1_Click(object sender, EventArgs e)??? {??????? BOOK bo1 = new BOOK();??????? bo1.dic.Add("hehe", "zhou");??????? bo1.dic.Add("haah", "li");??????? bo1.City = "chengdu";??????? using (MemoryStream ms = new MemoryStream())??????? {??????????? BinaryFormatter bf = new BinaryFormatter();??????????? bf.Serialize(ms, bo1);??????????? ms.Flush();??????????? ms.Position=0;??????????? Byte [] bts=new Byte[ms.Length];??????????? ms.Read(bts, 0, (int)ms.Length);??????????? Session["se"] = bts;??????? }??? ???? }
protected void Button1_Click(object sender, EventArgs e)??? {??????? Byte[] bts = (Byte[])Session["se"];??????? ??????? using (MemoryStream ms = new MemoryStream())??????? {??????????? ms.Position = 0;???????????? ms.Write(bts,0,bts.Length);??????????? BinaryFormatter bf = new BinaryFormatter();?????????? var book= (BOOK)bf.Deserialize(ms);//報(bào)錯(cuò)?????????? Response.Write(book.City + book.Age + book.river+book.dic["hehe"]);?????? ???????? }??? }
一個(gè)button是來設(shè)置把bo1對(duì)象轉(zhuǎn)換成Bytes數(shù)組,然后存在session中,后一個(gè)button用來讀取這個(gè)對(duì)象,但是這樣會(huì)報(bào)錯(cuò)的,錯(cuò)誤信息是“End of Stream encountered before parsing was completed.”如果使用MemoryStream ms = new MemoryStream(bts)就不會(huì)報(bào)錯(cuò)了 我想知道直接把bts賦給MemoryStream的構(gòu)造函數(shù)和用write方法寫進(jìn)去Memorystream有什么不一樣嗎?我記得前幾天把一個(gè)記事本中的一串字符通過binarywrite寫進(jìn)一個(gè)memorystream,直接用binaryread.readchar()得到的字符串和記事本也不一樣,是不是寫的時(shí)候加入了額外的比如編碼信息嗎?
2 回答

慕沐林林
TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
dudu 真好 !我就是看溫故知新學(xué)的流,吃飯時(shí)候想到了問題的原因:應(yīng)該說用write和構(gòu)造函數(shù)是一樣的只是在ms.Write(bts,0,bts.Length);之后ms的position屬性在最后,反序列化應(yīng)該是從最開始讀取才正確,所以需要在
var book= (BOOK)bf.Deserialize(ms);//報(bào)錯(cuò)之前加上ms.Position=0,試了 可以了
????? ? ? ?
- 2 回答
- 0 關(guān)注
- 387 瀏覽
添加回答
舉報(bào)
0/150
提交
取消