Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Compress and DeCompress of files using GZipStream in Asp.Net   You are not logged in.



CodeDigest Navigation

Technology News
No News Feeds available at this time.

Community News
No News Feeds available at this time.
Compress and DeCompress of files using GZipStream in Asp.Net

By Suresh Kumar Goudampally
Posted On Dec 18,2010
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 9
Print this article.
Category: ASP.Net

Subscribe to our feed!

Download Aspose, it really helps

Compress and Decompress of files using GZipStream in Asp.Net


In general we all know that we compress the data and post it to the web server and the server decompresses the data to process the request. This is done to optimize the server performance and gain the bandwidth benefit. In this article I will be explaining how to compress a file using GZipStream utility in .Net and post it to the server. And also how the server application decompresses the data and executes the request. I will be demonstrating the whole process using a windows form application which posts the compressed data to the Asp.Net application which is hosted on the IIS server.


Before further delving into the details, I would like to explain what GZipStream is. GZipStream is used to compress the data in gzip format. GZipStream compress with namespace System.IO.Compress. Sending the gzip compressed data to server reduces the file size and gets the bandwidth benefit. Using the GZipStream class we can work in such a way with data in memory, as well as in disk.


Client Code for compressing the file using C#.Net

Take a windows form application and drag a button on to the form. On the click event of the button write the following code.

string url = "http://server/GzipSample/Handler2.ashx";

            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);           

            myHttpWebRequest.Method = "POST";           

            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";                       

            myHttpWebRequest.Headers.Add("Content-Encoding", "gzip");

            //the above code creates an httpwebrequest and adds the required Headers to transfer the compressed data


            FileStream infile = new FileStream("E:\\sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);

            byte[] buffer = new byte[infile.Length];

            int count = infile.Read(buffer, 0, buffer.Length);

            if (count != buffer.Length)






            //the above code converts the filestream to bytes


            Stream newStream = myHttpWebRequest.GetRequestStream();

            GZipStream compressedzipStream = new GZipStream(newStream, CompressionMode.Compress);           

            compressedzipStream.Write(buffer, 0, buffer.Length);


            //The above code send the gzip compressed data the server as mentioned in the url


            HttpWebResponse httpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();


Take a sample file sample.txt  and put some data in the following format

Suresh Kumar

Satheesh Babu

Sravan Kumar



When you click the button and observe the fiddler the http request is sent in the following format

POST http://server/GzipSample/Handler2.ashx HTTP/1.1

Content-Type: application/x-www-form-urlencoded

Content-Encoding: gzip

Host: server

Content-Length: 145

Expect: 100-continue

Connection: Keep-Alive




Server code on the Asp.Net application to decompress the data

Write an HttpHandler Handler1.ashx to process the request. Write the following code to decompress the data.

Recent Articles

public void ProcessRequest(HttpContext context)


            String File = "C:\\Temp\\decompress.txt";

            using (StreamReader textReader = GetStreamReader(context))

            using (StreamWriter textWriter = new StreamWriter(File))


                String line = "";




                    line = textReader.ReadLine();

                } while (!line.Contains("End"));




            context.Response.ContentType = "text/plain";

            context.Response.Write("Hello World");


private static StreamReader GetStreamReader (HttpContext context)


            if (context.Request.Headers["Content-Encoding"] != null && context.Request.Headers["Content-Encoding"].Contains("gzip"))


                return new StreamReader(

                    new GZipStream(context.Request.InputStream, CompressionMode.Decompress));




                return new StreamReader(context.Request.InputStream);



Check the output file and compare with original file.



Though the Compression and Decompression is the familiar concept known to all, this article mainly speaks about basics of how to compress the data using GzipStream on the client application and post to the server.  And how the server application developed in Asp.Net receives the data and decompresses it.


Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Submitted By  
    Enter the verification number
    ( 2012.02.19 07:44
    ( 2012.02.19 07:44 ) : Hey I know this is off topic but I was wondering if you knew of any<a href=""> wgtdeis</a> I could add to my blog that automatically tweet my newest twitter updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.
    ( 2012.02.22 02:29
    ( 2012.02.22 02:29 ) : In line with my research, after a prrtoepy foreclosure home is bought at a bidding, it is common for that borrower in order to still have the remaining unpaid debt on the mortgage. There are many loan companies who seek to have all charges and liens paid back by the subsequent buyer. On the other hand, depending on selected programs, rules, and state laws and regulations there may be some loans that are not easily resolved through the transfer of loans. Therefore, the obligation still lies on the debtor that has obtained his or her prrtoepy in foreclosure. Thank you sharing your thinking on this website. [url=]nzupfj[/url] [link=]bmaruoj[/link]
    My husband and i got
    My husband and i got<a href=""> rlleay</a> lucky when John managed to conclude his web research because of the ideas he came across out of the weblog. It's not at all simplistic just to be giving out procedures that many other people have been trying to sell. We see we now have the blog owner to appreciate for this. The explanations you made, the straightforward blog navigation, the friendships you will help to create it is all fantastic, and it's<a href=""> rlleay</a> helping our son in addition to our family reason why that issue is fun, which is extraordinarily mandatory. Many thanks for the whole thing!
    Always rehfsering to
    Always rehfsering to hear a rational answer.
    IIZnJu , [url=]gqsoatfqkiwu[/url], [link=]xsnsppqngqko[/link],
    IIZnJu , [url=]gqsoatfqkiwu[/url], [link=]xsnsppqngqko[/link],
    RO7Bf7 <a href="">aicfcihzusfz</a>
    RO7Bf7 <a href="">aicfcihzusfz</a>
    uXozwq , [url=]pijgqzpbsilz[/url], [link=]xmyqnqeymqzm[/link],
    uXozwq , [url=]pijgqzpbsilz[/url], [link=]xmyqnqeymqzm[/link],
    Exactly What Are TheBeing around for many years of senieg my father struggle with the condition, I can tell you from the start that , known as hemorrhoids might be one of the most horrible problems
    Exactly What Are TheBeing around for many years of senieg my father struggle with the condition, I can tell you from the start that , known as hemorrhoids might be one of the most horrible problems an individual can possibly suffer from. I remember the sounds of suffering, as well as the inability to be a average human being, and I can recall the worries I had for my father, at the time he realised that the the one way to have some kind of hemorrhoids treatment, was to have them removed through surgery. This was something he would not even consider. Rather than that he dealt with so much of the related suffering, until finally he was hospitalised regarding a problem that was different, and they also scheduled him for last minute hemorrhoids operation.There are generally 5 different gradings regarding hemorrhoids, and certain ones are surely more severe than others. Approximately as many as 25 percent of men and women in the USA are suffering from one of the grading of hemorrhoids, and most do not ever check with their doctor in regards to the issue. This will make it really difficult to see virtually any conclusive research studies as to what is the best method to deal with the ailment. Almost all general practitioners, whenever they do at some point observe cases of hemorrhoids start out with the application of a good quality hemorrhoids ointment. Once again though, it just depends on the type of hemorrhoids you happen to be having.Some hemorrhoids signs or symptoms may include: painless or perhaps painful bleeding hemorrhoids attached through the rectum, itchy spots close to your rectum, swelling, as well as tenderness right after a bowel movement. Any of those issues may well be a case of hemorrhoids, and you ought to truly have the issue looked at by a physician any time any of these signs and symptoms begin to be present. The hazards associated with unchecked may be significantly more serious.If you feel or perhaps are certain that you could have hemorrhoids, there are many of ways that you could relieve the symptoms, with a solution to correcting the issue entirely, based on precisely how bad you've got them presently. A warm bath may soothe away the pain that you may possibly be dealing with, however when this is effective it's only effective while the discomfort lasts. Warm baths won't cure this problem. When you're having a bowel movement, do not strain or push too much. This will likely irritate your hemorrhoids, and cause more pain.The product range associated with hemorrhoids treatment options is quite extensive, and they are each only effective on the grade of hemorrhoids that you are suffering from, except surgery that is. There are many ointments and also medicinal lotions to apply to grade 1 and 2 hemorrhoids. There is a procedure called banding, which involves the doctor putting a band around the top of the hemorrhoids, effectively cutting off the blood circulation towards the hemorrhoids treatment, and finally making them fall off. This could take some days, and is really only used with Grade 2 hemorrhoids. Certainly the best solution is surgery, so if you're concerned with the condition of life you have whilst battling this problem, particularly bleeding hemorrhoids, then you're best advised to talk with your doctor at the earliest opportunity to allow them to help make the right choice on your behalf.
    PicSpr , [url=]orpodlbfaedo[/url], [link=]lircupoeiukw[/link],
    PicSpr , [url=]orpodlbfaedo[/url], [link=]lircupoeiukw[/link],