Create new account I forgot my password    

Read and Write compressed data to a binary file using ASP.NET
Rating: 12 user(s) have rated this article Average rating: 4.3
Posted by: Suprotim Agarwal, on 9/13/2008, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 20490 times
Abstract: The BinaryReader and BinaryWriter in System.IO namespace read and write primitive types in binary, to a stream. The System.IO.Compression.GZipStream provides methods and properties to compress and decompress the stream. In this article, we will learn how to use compression techniques to compress the stream and write it to a binary file. We will then use the BinaryReader and the GZipStream class to decompress and read the file to display it on the webpage.

Read and Write compressed data to a binary file using ASP.NET
 
The BinaryReader and BinaryWriter in System.IO namespace read and write primitive types in binary, to a stream. The System.IO.Compression.GZipStream provides methods and properties to compress and decompress the stream. In this article, we will learn how to use compression techniques to compress the stream and write it to a binary file. We will then use the BinaryReader and the GZipStream class to decompress and read the file to display it on the webpage.
We have different types of  files on our computer. The Binary file is one such format. You cannot read these binary files by just opening them in the notepad. In this article, we will use the classes BinaryWriter and BinaryReader to add information to the file and to retrieve information from it. We will be using a FileStream constructor to open and modify the file if it already exists, or create a new file if it does not exist. You can then pass the FileStreamobject and use it to construct your BinaryReader and BinaryWriter. Let us see some code:
 
Read and Writing Binary Files Without Compression
Note: Use the namespaces System.IO
Writing Binary data
C#
string str = "Read and Write compressed data to a binary file”;
// Write to a binary file
        FileStream fs = null;
        BinaryWriter bw = null;
        try
        {
            fs = new FileStream(@"C:\test.bin", FileMode.OpenOrCreate);
            bw = new BinaryWriter(fs);
            bw.Write(str);          
        }
        catch (IOException ex)
        {
 
        }
        finally
        {
            bw.Flush();
            bw.Close();
            fs.Close();
        }
VB.NET
 
Dim str as string = "Read and Write compressed data to a binary file”
' Write to a binary file
            Dim fs As FileStream = Nothing
            Dim bw As BinaryWriter = Nothing
            Try
                  fs = New FileStream("C:\test.bin", FileMode.OpenOrCreate)
                  bw = New BinaryWriter(fs)
                  bw.Write(str)
            Catch ex As IOException
 
            Finally
                  bw.Flush()
                  bw.Close()
                  fs.Close()
            End Try
Reading Binary Data
C#
// Read from a binary file
        FileStream fs1 = null;
        BinaryReader br = null;
        try
        {
            fs1 = new FileStream(@"C:\test.bin", FileMode.Open);
            br = new BinaryReader(fs1);
            string str1;
            str1 = br.ReadString();
            Response.Write(str1);
        }
        catch (IOException ex)
        {
 
        }
        finally
        {
            br.Close();
            fs1.Close();
        }       
VB.NET
' Read from a binary file
            Dim fs1 As FileStream = Nothing
            Dim br As BinaryReader = Nothing
            Try
                  fs1 = New FileStream("C:\test.bin", FileMode.Open)
                  br = New BinaryReader(fs1)
                  Dim str1 As String
                  str1 = br.ReadString()
                  Response.Write(str1)
            Catch ex As IOException
 
            Finally
                  br.Close()
                  fs1.Close()
            End Try
 
Read and Writing Binary Files Using Compression
Note: Use the namespaces System.IO.Compression. Here instead of passing the file stream object directly to the BinaryWriter, we are passing the stream to GZipStream to compress it. The compressed stream is then passed to BinaryWriter. Similarly while reading the file, we pass the stream to GZipStream to decompress and then use BinaryReader to read the file and display its contents.
Writing Binary data
C#
// Compress and write to a binary file
        FileStream fs = null;
        BinaryWriter bw = null;
        try
        {
            fs = new FileStream(@"C:\test1.bin", FileMode.OpenOrCreate);
            GZipStream cmp = new GZipStream(fs, CompressionMode.Compress);
            bw = new BinaryWriter(cmp);
            bw.Write(str);
        }
 
        catch (IOException ex)
        {
 
        }
        finally
        {
            bw.Flush();           
            bw.Close();
            fs.Close();
        }
VB.NET
' Compress and write to a binary file
            Dim fs As FileStream = Nothing
            Dim bw As BinaryWriter = Nothing
            Try
                  fs = New FileStream("C:\test1.bin", FileMode.OpenOrCreate)
                  Dim cmp As GZipStream = New GZipStream(fs, CompressionMode.Compress)
                  bw = New BinaryWriter(cmp)
                  bw.Write(str)
 
            Catch ex As IOException
 
            Finally
                  bw.Flush()
                  bw.Close()
                  fs.Close()
            End Try
Reading Binary Data
C#
// Decompress and read from a binary file
        FileStream fs1 = null;
        BinaryReader br = null;
        try
        {
            fs1 = new FileStream(@"C:\test1.bin", FileMode.Open);
            GZipStream dcmp = new GZipStream(fs1,
                CompressionMode.Decompress);
            br = new BinaryReader(dcmp);
            string str1;
            str1 = br.ReadString();
            Response.Write(str1);
        }
        catch (IOException ex)
        {
 
        }
        finally
        {
            br.Close();
            fs1.Close();
        }  
VB.NET
' Decompress and read from a binary file
            Dim fs1 As FileStream = Nothing
            Dim br As BinaryReader = Nothing
            Try
                  fs1 = New FileStream("C:\test1.bin", FileMode.Open)
                  Dim dcmp As GZipStream = New GZipStream(fs1, CompressionMode.Decompress)
                  br = New BinaryReader(dcmp)
                  Dim str1 As String
                  str1 = br.ReadString()
                  Response.Write(str1)
            Catch ex As IOException
 
            Finally
                  br.Close()
                  fs1.Close()
            End Try
In this article, we saw how to use compression techniques to compress the stream and write it to a binary file. We then used the BinaryReader and the GZipStream class to decompress the stream and read the file to display it on the webpage. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Defcon on Monday, September 15, 2008 4:49 AM
Thanks alot for this info.
Helped me alot..

but if you check the size of the 2 generated files:
test.bin  ->  96 bytes
test1.bin -> 158 bytes
so the compressed one is more than 50% bigger than the not compressed one :)

please elaborate..
Comment posted by Thargol on Tuesday, September 16, 2008 5:54 AM
Error in de error-handling:
In the part:
Finally
  bw.Flush()
  bw.Close()
  fs.Close()
End Try

If the line fs = New FileStream("C:\test1.bin", FileMode.OpenOrCreate) throws an exception then 'bw' is not created and the call to bw.flush() will fail.

Why not use a 'using'-contruct instead of try-finally?

Comment posted by Suprotim Agarwal on Tuesday, September 16, 2008 9:27 AM
Defcon: Let me try the sample and get back to you. That sounds funny :) Have you tried it with a larger set of data?

Thargol: Yes, I overlooked that. the 'using' block would be more cleaner and efficient. THanks.
Comment posted by Defcon on Wednesday, September 17, 2008 3:36 AM
Agarwal: no, i've only tested this with your String(str) :)
Comment posted by Anonymous on Monday, September 29, 2008 9:34 PM
The article title "Read and Write compressed data to a binary file using ASP.NET" would seem to indicate that one is Reading and Writing Binary Data on an ASP.Net Web Page NOT on a local hard drive... close to what I need but NOT good enough.

DOH!

>:(

Comment posted by Carlos de la Puente on Thursday, October 30, 2008 1:27 AM
GZipStream adds 104 bytes to the resulting stream. So, compressing a rather small stream wouldn't be worth the while. It seems that anything smaller than 4K is probably not worth compressing. In any case, compressing binary data (consisting of mostly random byte values) will invariably result in a larger stream (generally 50% larger). This is true even if the binary data is not in some already-compressed format (such as JPEG or PDF). The same holds true for DeflateStream (both do the same compression, GZipStream just ends up with 4 more bytes). They do better at compressing Text, even if it is rather random.

The following code example demonstrates this:

for (int p = 0; p < 3; p++)
{
    for (int i = 100; i <= 1000000; i *= 10)
    {
        byte[] b;
        switch (p)
        {
            case 0:
                b = new byte[i];
                new Random().NextBytes(b);
                if (i == 100)
                    Console.WriteLine("Random Binary:\t{0}...", BitConverter.ToString(b, 0, 10));
                break;
            case 1:
                b = new byte[i / 2];    // will end up being same length after converting to chars
                new Random().NextBytes(b);
                string s = BitConverter.ToString(b).Replace("-", "");
                b = Encoding.UTF8.GetBytes(s);
                if (i == 100)
                    Console.WriteLine("Random Text:\t{0}...", BitConverter.ToString(b, 0, 10));
                break;
            default:
                b = new byte[i];
                if (i == 100)
                    Console.WriteLine("All Zeroes:\t{0}...", BitConverter.ToString(b, 0, 10));
                break;
        }
        using (MemoryStream ms = new MemoryStream())
        {
            using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress, true))
            {
                zs.Write(b, 0, b.Length);
                Console.WriteLine("\tOriginal: {0} bytes, Compressed: {1} bytes", b.Length, ms.Length);
            }
        }
    }
}
Console.Read();
Comment posted by Suprotim Agarwal on Thursday, October 30, 2008 10:44 AM
That was a good explanation Carlos. I completely missed updating this comment even after trying out the tests. Apologies and thanks for giving your comment for future users!
Comment posted by prakash gupta on Friday, March 06, 2009 7:11 AM
Hi it help me lots..thanks
but if i want to update values of binary file
then what should I have to do?

thanks
prakash gupta
Comment posted by Suprotim Agarwal on Sunday, March 08, 2009 8:39 AM
Prakash: I haven't tried it but what makes sense is that if the file is on the disk, use FileMode.Append and the save the new data to the existing one.

If it is in the database, do it the way shown over here: http://www.asp.net/learn/data-access/tutorial-57-cs.aspx
Comment posted by hgj on Thursday, June 25, 2009 4:52 AM
tyut

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER