GZipStream Compress And Decompress

static string dir = @"D:\C\ConsoleApp2";
        static void GZipCompressDemo()
        {            
            string[] filesArr = Directory.GetFiles(dir, "*", SearchOption.AllDirectories);
            if(filesArr!=null && filesArr.Any())
            {
                for(int i=0;i<filesArr.Length;i++)
                {
                    string fileName = Path.GetFileNameWithoutExtension(filesArr[i]);
                    string gzipFileName = fileName + ".gz";
                    using(FileStream originalStream=File.Open(filesArr[i],FileMode.Open))
                    {
                        using (FileStream outStream = new FileStream(gzipFileName, FileMode.Create))
                        {
                            Console.WriteLine(gzipFileName);
                            using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
                            {
                                originalStream.CopyTo(gzipStream);
                            }
                        }
                    }                   
                }
            }
        }

        static void GZipDecompressDemo()
        { 
            string[] gzippedFilesArr= Directory.GetFiles(dir, "*.zip", SearchOption.AllDirectories);
            if(gzippedFilesArr!=null && gzippedFilesArr.Any())
            {
                for(int i=0;i<gzippedFilesArr.Length;i++)
                {
                    string fileName = Path.GetFileNameWithoutExtension(gzippedFilesArr[i])+".unzip";  
                    if(File.Exists(fileName))
                    {
                        return;
                    }
                    using (FileStream originalStream = File.Open(gzippedFilesArr[i], FileMode.Open))
                    {
                        using (FileStream decompressedFileStream = File.Create(fileName))
                        {
                            Console.WriteLine(fileName);
                            using (GZipStream unzipStream = new GZipStream(originalStream, CompressionMode.Decompress))
                            {
                                unzipStream.CopyTo(decompressedFileStream);
                            }
                        }
                    }                   
                }
            }
        }

 

posted @ 2020-06-08 15:45  FredGrit  阅读(186)  评论(0编辑  收藏  举报