2008-11-26 88 views
2

編輯:關閉這個,因爲我發現它的原因爲錯誤,但不是刪除這個帖子..我生成一個更新的帖子,更精確的問題。反序列化拋出這個位的C#代碼異常


嗨夥計,

我有一些二進制數據我在讀我的心願。將其轉換爲一個System.Drawing.Image,所以我創建Image object的實例,使用memory stream作爲輸入數據。

我這樣做後,我序列化然後反序列化圖像(對於一些業務邏輯)。反序列化引發異常。如果我使用文件名構造函數而不是內存流構造函數創建Image實例,它將全部工作100%。這表明Image對象可以通過電線串行化。

我做錯了memory stream,我用過了嗎?

這是我使用使圖像對象的代碼,它被序列之前: -

// Fake way of getting some binary (image) data. 
byte[] data = File.ReadAllBytes("Chick.jpg"); 

using (Stream originalBinaryDataStream = new MemoryStream(data)) 
{ 
    // This works perfectly fine, if use this method (which i can't). 
    //image = new Bitmap("Chick.jpg"); 

    // This throws an exception when it's deserialized. 
    // It doesn't like the memory stream reference? 
    image = new Bitmap(originalBinaryDataStream);  
} 

這是一種嘗試反序列化圖像,其拋出異常代碼(this is a seperate image of the exception

alt text http://img254.imageshack.us/img254/9748/step1zx3wk5.png

有沒有正確處理或不能序列化..因此拋出異常?

請幫助:)


編輯:唯一的例外是在叫我圖像調試器可視

我已經上傳完整的VS2008解決方案here(1.28MB下載)。

在它是兩個項目 - >的可視化類MS測試類。如果你運行唯一的單元測試,它會拋出泛型(讀:無用)GDI +異常,因爲它無法反序列化通過線路傳遞給調試器的圖像實例。如果您將它傳遞給使用文件路徑構造函數創建的Image實例,則反序列化完美運行。

編輯2:使用不同的文件上傳網站 - 歡呼!

編輯3:如何實際重現錯誤。

  • 更改項目,在調試模式(而不是釋放模式)
  • 刪除所有破發點。
  • 打開ImageDebuggerVisualizer.cs
  • 添加斷點到管線22
  • 現在調試的UnitTest1單元測試方法。圖像將顯示..關閉該窗口..然後突然你將在折點上。一步一步和繁榮! CRASH!砰。

編輯4:這裏有兩個SCREEN SHOTS的例外(如果你不想下載解決方案文件)。

+0

你會得到什麼例外? – 2008-11-26 12:36:08

+0

我們需要整個代碼的上下文和引發的異常。 – 2008-11-26 12:56:23

+0

提供的解決方案鏈接:) – 2008-11-26 13:10:42

回答

2

剛剛測試過你的代碼,它的工作,代碼是好的。圖像文件或路徑必須存在問題。 這是我的測試:

private void Form1_Load(object sender, EventArgs e)  
     { 
      byte[] data = File.ReadAllBytes("c:\\t.jpg"); 

      using (Stream originalBinaryDataStream = new MemoryStream(data)) 
      { 
       // This works perfectly fine, if use this method (which i can't). 
       //image = new Bitmap("Chick.jpg"); 


       // This throws an exception when it's deserialized. 
       // It doesn't like the memory stream reference? 
       originalBinaryDataStream.Seek(0, SeekOrigin.End); 
       pictureBox1.Image= new Bitmap(originalBinaryDataStream); 
      } 
     } 

而且我看到在圖片框的圖像。

3

我懷疑在你的真實代碼中,你正在寫入MemoryStream而不是倒回它;如果是這種情況,請在嘗試重新加載之前將位置設置爲0。

0

我已經更新了一個鏈接整個VS解決方案(這是一個類和一個單元測試)的初始問題。單元測試會引發失敗失敗失敗異常。請檢查一下。