递归方法遍历 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 private int statisticFiles (string directory ) { int statistic=System.IO.Directory.GetFiles(directory).Length; string [] directories = System.IO.Directory.GetDirectories(directory); foreach (string dir in directories) { if (isDirectory(dir)) { statistic += statisticFiles(dir); } else { MessageBox.Show("Directory is Inexistence." ); } } return statistic; } private static bool isDirectory (string p ) { return System.IO.Directory.Exists(p); }
遍历特定目录及其子目录 (应用实例,压缩指定目录下的所有文件) 这是我迄今所知的最简单的压缩方法。使用了Java类库。
注意:必须在项目中添加对vjslib引用,程序才能通过编译。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 { String strDirectory = @"E:/工作" ; static void Main (string [] args ) { String zipFileName = "E://workBackup//" + DateTime.Now.ToString("yy_MM_dd" ) + ".zip" ; java.io.FileOutputStream fos = new java.io.FileOutputStream(zipFileName); 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." ); } 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) { fis = new java.io.FileInputStream(strfileName); String strZipFileName = strfileName.Replace(strDirectory+"//" , "" ); ze = new java.util.zip.ZipEntry(strZipFileName); zos.putNextEntry(ze); sbyte [] buffer = new sbyte [1024 ]; int len; while ((len = fis.read(buffer)) >= 0 ) { zos.write(buffer, 0 , len); } fis.close(); } String[] subDirectories = System.IO.Directory.GetDirectories(dir); foreach (String sdir in subDirectories) { zipFiles(sdir, zos); } } }
相关链接(侵删)
C# 趣味小程序(4)——遍历特定目录及其子目录
续:C# 趣味小程序(4)——遍历特定目录及其子目录 (应用实例,压缩指定目录下的所有文件)
=================我是分割线=================
欢迎到公众号来唠嗑: