Read and Write compressed data to a binary file using ASP.NET

Posted by: Suprotim Agarwal , on 9/13/2008, in Category ASP.NET
Views: 69672
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.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and the C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
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 6, 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 8, 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
Comment posted by Kel on Thursday, January 5, 2012 9:19 PM
Thanks for your article.
I am reading binary data (data type = image) from SQL database and try to write into the file again.
The file i create will always have strange character at the first character. any idea?
Thanks

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook