Compressing Method loses one or more bytes VB.NET

Following is the code I am using for compression and decompression purposes. My goal is to convert a datatable into XML and then to binary compressed format and then read it back and convert the binary back to XML. So, basically, I am converting XML into Binary Compressed and then Compressed binary back into XML. Logically, the data sizes should be same but the new decompressed XML file loses one byte or more for some reason. Can you guys help me out.

Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO.Compression
Imports System.Data.SqlClient
Imports System.Data.Sql

Public Class Form1
Dim dt As New SmExplorerDataDataSet.smedataDataTable
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim ta As New SmExplorerDataDataSetTableAdapters.smedataTableAdapter

    'Read the XML file and compress it
    Dim in_fs As FileStream = New FileInfo("abc.xml").OpenRead
    Dim out_fs As FileStream = File.Create("def.cmp")
    in_fs.CopyTo(New DeflateStream(out_fs, CompressionMode.Compress))

    'Read the compressed file and decompress it back into XML
    in_fs = New FileStream("def.cmp", FileMode.Open, FileAccess.Read)
    out_fs = New FileStream("abc2.xml", FileMode.OpenOrCreate, FileAccess.Write)
    Dim DFS As DeflateStream = New DeflateStream(in_fs, CompressionMode.Decompress)
End Sub
End Class

In the first XML (original file), the ending line ends the documentelement tag properly like DocumentElement BUT in the new decompressed XML file, the last few characters are missing from this tag and it looks like following DocumentElem This causes an error when i try to read it again. Kindly assist.


  • 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)
            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)
            End Using
        End Using
    End Using