Conversion from Binary Data to XML using VB.net

1.2k views Asked by At

I am trying to retrieve a VARBINARY column from SQL and then convert the binary data into XML. I can retrieve the data easily and also convert it to XML but recently it started truncating the last few characters of the converted XML file. Below is the code and description.

This is how I retrieve the binary Data.

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

Then, I convert it into MemoryStream.

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

Then, I decompress it (since it was in compressed mode).

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()

But, it truncates the last few characters from xml file. (XMLdataReader is just a string containing file name). Below is the truncated result. I want it to be complete since i want to convert that XML into a data table.

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

Can you guys kindly help. I have googled this a lot and I don't ask questions until I am sure that I am just going in circles. Apart from this, is there anyway that I can convert this decompressed binary data into XML without having to save it in file and then convert it into datatable. Thanks Guys. :)

1

There are 1 answers

0
Name changed to mask identity On BEST ANSWER

Always use Using with IDisposable resources to avoid this kind of issue:

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