欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用Deflate算法对文件进行压缩与解压缩的方法详解

程序员文章站 2023-12-19 17:54:52
如下所示:复制代码 代码如下:        static void main() &nbs...
如下所示:
复制代码 代码如下:

        static void main()
        {
            string path = @"d:\practise\io\compress";
            string decompresspath = @"d:\practise\io\decompress";
            directoryinfo dir = new directoryinfo(path);
            foreach (fileinfo fi in dir.getfiles())
            {
                compress(fi);
            }
            foreach (fileinfo fi in dir.getfiles("*.cmp"))
            {
                decompress(fi, decompresspath);
            }
        }
        public static void compress(fileinfo fi)
        {
            using (filestream fs = fi.openread())
            {
                if (fi.attributes != fileattributes.hidden & fi.extension != ".cmp")
                {
                    using (filestream compressfile = new filestream(fi.fullname + ".cmp", filemode.create, fileaccess.readwrite))
                    {
                        using (deflatestream ds = new deflatestream(compressfile, compressionmode.compress))
                        {
                            fs.copyto(ds);
                            console.writeline("this file {0} has been compressed to {1}",fi.name,compressfile.name);
                        }
                    }
                }
            }
        }
        public static void decompress(fileinfo fi, string desination)
        {
            using (filestream fs = fi.openread())
            {
                string decompressfile = fi.name.remove(fi.name.length - fi.extension.length);
                using (filestream decompressfs = new filestream(path.combine(desination, decompressfile), filemode.create, fileaccess.readwrite))
                {
                    using (deflatestream ds = new deflatestream(fs, compressionmode.decompress))
                    {
                        ds.copyto(decompressfs);
                        console.writeline("this file {0} has been decompressd", fi.name);
                    }
                }
            }
        }

上一篇:

下一篇: