When using gzipstream for compression, you must call the close () method at the end. Otherwise, you will find that one byte is missing after decompression. When the compressed file is smaller than 4 kb, the decompressed file is 0 in length.
The following is a complete compressed and decompressed FileCodeFor reference:
Private Void Button#click ( Object Sender, eventargs e ){ String Filename = textbox1.text; // @ "F: \ response.txt "; Fileinfo fi = New Fileinfo (filename); listbox1.items. Add ( " Source file length: " + Fi. length. tostring ()); Byte [] Buf = Compress (filename); listbox1.items. Add (string. Format ( " Compress length: {0}, compress rate: {1: F2} % " , Buf. length ,( Double ) BUF. length * 100 /( Double ) Fi. Length )); String Newfilename = string. Format ( @" {0} \ {1} _ new {2} " , Path. getdirectoryname (filename), path. getfilenamewithoutextension (filename), path. getextension (filename); listbox1.items. Add ( " Decompress length: " + Decompress (BUF, newfilename). tostring ());} Public Static Byte [] Compress (String Filename ){ // Compressed memorystream Memorystream MS = New Memorystream (); // Write Compression Gzipstream compressedstream = New Gzipstream (MS, compressionmode. Compress, True ); Filestream FS = New Filestream (filename, filemode. Open ); Byte [] Buf = New Byte [ 1024 ]; Int Count = 0 ; Do {Count = FS. Read (BUF, 0 , Buf. Length); compressedstream. Write (BUF, 0 , Count );} While (Count> 0 ); FS. Close (); compressedstream. Close (); Return Ms. toarray ();} Public Static Int Decompress ( Byte [] Data, String Filename ){ Int Iret =0 ; Byte [] Buf = New Byte [ 1024 * 1024 ]; Try {Filestream FS = New Filestream (filename, filemode. Create); memorystream MS = New Memorystream (data); gzipstream decompressedstream = New Gzipstream (MS, compressionmode. decompress, True ); Int Count = 0 ; Do {Count = Decompressedstream. Read (BUF, 0 , Buf. Length); FS. Write (BUF, 0 , Count); FS. Flush ();} While (Count> 0 ); Iret = ( Int ) Fs. length; FS. Close ();} Finally {} Return Iret ;} Private Void Button3_click (Object Sender, eventargs e) {openfiledialog Dialog = New Openfiledialog () {initialdirectory = Environment. currentdirectory, multiselect = False ,}; If (Dialog. showdialog () = Dialogresult. OK) {textbox1.text = Dialog. filename ;}}