My latest project required the application to uncompress a bunch of gzip files. I decided to create a class to meet this requirement. Here is example of how to uncompress a gzip file.
01.using System;
02.using System.IO;
03.using System.IO.Compression;
04.
05.namespace SaludaLabs.IDX
06.{
07. public class SaludaGzip
08. {
09. private String _srcFile;
10. private String _dstFile;
11. public string SrcFile
12. {
13. get { return _srcFile; }
14. set { _srcFile = value; }
15. }
16.
17. public string DstFile
18. {
19. get { return _dstFile; }
20. set { _dstFile = value; }
21. }
22.
23. public SaludaGzip()
24. {
25. //do nothing here
26. }
27.
28. public SaludaGzip(string filein, string fileout)
29. {
30. SrcFile = filein;
31. DstFile = fileout;
32. }
33.
34. public void Douncompress()
35. {
36. FileStream fileIn = null;
37. FileStream fileOut = null;
38.
39. GZipStream gzip = null;
40. const int bufferSize = 4096;
41. byte[] buffer = new byte[bufferSize];
42. int count = 0;
43.
44. try
45. {
46. fileIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
47. fileOut = new FileStream(DstFile, FileMode.Create, FileAccess.Write, FileShare.None);
48.
49. gzip = new GZipStream(fileIn, CompressionMode.Decompress, true);
50. while (true)
51. {
52. count = gzip.Read(buffer, 0, bufferSize);
53. if (count != 0)
54. {
55. fileOut.Write(buffer, 0, count);
56. }
57. if (count != bufferSize)
58. {
59. //have reaqched the end
60. break;
61. }
62. }
63. }
64. catch (Exception ex)
65. {
66. //needs some future code here to handle exceptions
68. }
69. finally
70. {
71. if (gzip != null)
72. {
73. gzip.Close();
74. gzip = null;
75. }
76. if (fileOut != null)
77. {
78. fileOut.Close();
79. fileOut = null;
80. }
81. if (fileIn != null)
82. {
83. fileIn.Close();
84. fileIn = null;
85. }
86. }
87. }
88. }
89.}
To use the class, I first created an object.
SaludaGzip fileunzip = new SaludaGzip();
After creating the object, I just pass in the gzip file name, and the new file name minus gzip.
fileunzip.SrcFile = Server.MapPath(filename);
fileunzip.DstFile = Server.MapPath(newfilename);
fileunzip.Douncompress();
I was able to use this to compress an entire folder of compress files by using foreach loop of directory for the file name. example: someinfo.txt.gzip After I got the file name, I just did a substring to take out the gzip. example: someinfo.txt.
The class is working great for the project.