GZipStream
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)
{
infile.Close();
return;
}
infile.Close();
//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);
compressedzipStream.Close();
//The above code
send the gzip compressed data the server as mentioned in the url
HttpWebResponse httpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
httpWebResponse.Close();
Take a sample file sample.txt and put some data
in the following format
Suresh Kumar
Satheesh Babu
Sravan Kumar
End
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
_?_?????_??_`_I?%&/m?{J?J??t?_?`_$?@_??????_iG#)?*??eVe]f_@????{???{???;?N'????\fd_l??J??!???_?~|_?"^?????z??q_??????~??t9??_?_&???
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.
|