使用VB.net从二进制数据转换为XML

时间:2014-12-04 15:33:03

标签: xml vb.net binary compression deflatestream

我正在尝试从SQL检索VARBINARY列,然后将二进制数据转换为XML。我可以轻松地检索数据并将其转换为XML,但最近它开始截断转换后的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,而不必将其保存在文件中,然后将其转换为数据表。 多谢你们。 :)

1 个答案:

答案 0 :(得分: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
相关问题