2014-12-04 44 views
0

我想從SQL中檢索一個VARBINARY列,然後將二進制數據轉換爲XML。我可以輕鬆地檢索數據並將其轉換爲XML,但最近它開始截斷轉換的XML文件的最後幾個字符。以下是代碼和說明。使用VB.net從二進制數據轉換爲XML

這是我如何檢索二進制數據。

Dim binaryData As Byte() 
sqlData.Open() 
     binaryCMD.CommandText = "select photo from dbo.testing_filestream where clientName = '" & clientSelected1 & "' and date = '" & minimumDate & "'" 
     binaryCMD.CommandType = CommandType.Text 
     binaryCMD.Connection = sqlData 
     binaryData = binaryCMD.ExecuteScalar 

然後,我將它轉換成MemoryStream。

Dim xmlStream As New IO.MemoryStream(binaryData) 
      xmlStream.Seek(0, 0) 

然後,我解壓縮它(因爲它是壓縮模式)。

Dim out_fs = New FileStream(XMLdataReader, FileMode.OpenOrCreate, FileAccess.Write) 
      Dim unZip As DeflateStream = New DeflateStream(xmlStream, CompressionMode.Decompress) 
      unZip.CopyTo(out_fs) 
      unZip.Close() 
      out_fs.Close() 

但是,它截斷了xml文件中的最後幾個字符。 (XMLdataReader只是一個包含文件名的字符串)。以下是截斷的結果。我希望它是完整的,因爲我想將該XML轉換爲數據表。

</DocumentEle 
Whereas, it should give this in the format of 
</DocumentElement> 

你們可以幫忙嗎?我已經搜索了很多,直到我確信我只是在圈子裏,我纔會問問題。除此之外,無論如何,我可以將此解壓縮的二進制數據轉換爲XML,而無需將其保存在文件中,然後將其轉換爲數據表。 謝謝你們。 :)

+0

使用SQL參數和** **不使用字符串日期值 – Plutonix 2014-12-04 15:34:43

+0

好了,謝謝。我會改變它,但它會檢索數據正常。我已經將二進制數據導出到一個.cmp文件,並將它與原始文件進行比較,它是相同的。它只是截斷XML的最後幾個單詞。你能幫我解決嗎? – 2014-12-04 15:39:58

回答

0

始終使用IDisposable的資源使用,以避免這種問題:

Using in_fs = File.OpenRead("abc.xml") 
Using out_fs = File.Create("def.cmp") 
    Using df_fs = New DeflateStream(out_fs, CompressionMode.Compress) 
     in_fs.CopyTo(df_fs) 
    End Using 
End Using 
End Using 

Using in_fs = File.OpenRead("def.cmp") 
Using out_fs = File.Create("abc2.xml") 
    Using df_fs = New DeflateStream(in_fs, CompressionMode.Decompress) 
     df_fs.CopyTo(out_fs) 
    End Using 
End Using 
End Using