续:C# 趣味小程序(4)——遍历特定目录及其子目录 (应用实例,压缩指定目录下的所有文件)

这是我迄今所知的最简单的压缩方法。使用了Java类库。

注意:必须在项目中添加对vjslib引用,程序才能通过编译。

     {

      String strDirectory = @"E:/工作";
        static void Main(string[] args)
        {
            String zipFileName = "E://workBackup//" + DateTime.Now.ToString("yy_MM_dd") + ".zip";
            //output stream
            java.io.FileOutputStream fos = new java.io.FileOutputStream(zipFileName);
            //tie to zip stream
            java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(fos);
 
 
            Program p = new Program();
            Console.WriteLine("Enter a Directory/'s Name:" );
            p.strDirectory = System.Console.ReadLine();

            if (isDirectory(p.strDirectory))
            {
                p.zipFiles(p.strDirectory, zos);
            }
            else
            {
                Console.WriteLine("Directory is Inexistence.");
            }

            // Close everything
            zos.closeEntry();
            zos.close();
            fos.close();
        }

        private static bool isDirectory(string p)
        {
            return System.IO.Directory.Exists(p);
        }

        private void zipFiles(String dir, java.util.zip.ZipOutputStream zos)
        {
            java.io.FileInputStream fis = null;
            java.util.zip.ZipEntry ze = null;

            //压缩目录中的文件
            String[] strFiles = System.IO.Directory.GetFiles(dir);
            foreach (String strfileName in strFiles)
            {
                // Stream with source file
                fis = new java.io.FileInputStream(strfileName);
                // It's our entry in zip
                String strZipFileName = strfileName.Replace(strDirectory+"//", "");
                ze = new java.util.zip.ZipEntry(strZipFileName);

                zos.putNextEntry(ze);
                sbyte[] buffer = new sbyte[1024];
                int len;

                // Read and write until done
                while ((len = fis.read(buffer)) >= 0)
                {
                    zos.write(buffer, 0, len);
                }

                //Close source stream
                fis.close();
            }
            //深度优先遍历子目录
            String[] subDirectories = System.IO.Directory.GetDirectories(dir);
            foreach (String sdir in subDirectories)
            {
                zipFiles(sdir, zos);
            }

        }
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值