Guest User

Untitled

a guest
Apr 27th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.57 KB | None | 0 0
  1. private void ZipBaks()
  2. {
  3. try
  4. {
  5. // Make sure directories exist
  6. if (!Directory.Exists(BakPath))
  7. Directory.CreateDirectory(BakPath);
  8. if (!Directory.Exists(BakZipPath))
  9. Directory.CreateDirectory(BakZipPath);
  10. // Clean up old zip files
  11. string[] bakfiles = Directory.GetFiles(BakPath, "*" + BakExtension);
  12. string[] bakzipfiles = Directory.GetFiles(BakZipPath, "*" + ZipExtension);
  13. foreach (string bakzipfile in bakzipfiles)
  14. {
  15. string bakzipfilename = bakzipfile.Substring(bakzipfile.LastIndexOf(@"\") + 1);
  16. string bakfilename = bakzipfilename.Substring(0, bakzipfilename.LastIndexOf('.'));
  17. if (!File.Exists(BakPath + @"\" + bakfilename))
  18. {
  19. ToLog("Deleting Zip File: " + bakzipfile);
  20. File.Delete(bakzipfile);
  21. }
  22. }
  23. // Create new zip files as necssary
  24. foreach (string bakfile in bakfiles)
  25. {
  26. string ZipFile = BakZipPath + @"\" + bakfile.Substring(bakfile.LastIndexOf(@"\") + 1) + ZipExtension;
  27. if (!File.Exists(ZipFile))
  28. {
  29. ToLog("Creating Zip File: " + ZipFile);
  30. using (ZipOutputStream s = new ZipOutputStream(File.Create(ZipFile)))
  31. {
  32.  
  33. s.SetLevel(9); // 0 - store only to 9 - means best compression
  34.  
  35. byte[] buffer = new byte[4096];
  36.  
  37. // Using GetFileName makes the result compatible with XP
  38. // as the resulting path is not absolute.
  39. ZipEntry entry = new ZipEntry(Path.GetFileName(bakfile));
  40.  
  41. // Setup the entry data as required.
  42.  
  43. // Crc and size are handled by the library for seakable streams
  44. // so no need to do them here.
  45.  
  46. // Could also use the last write time or similar for the file.
  47. entry.DateTime = DateTime.Now;
  48. s.PutNextEntry(entry);
  49.  
  50. using (FileStream fs = File.OpenRead(bakfile))
  51. {
  52.  
  53. // Using a fixed size buffer here makes no noticeable difference for output
  54. // but keeps a lid on memory usage.
  55. int sourceBytes;
  56. do
  57. {
  58. sourceBytes = fs.Read(buffer, 0, buffer.Length);
  59. s.Write(buffer, 0, sourceBytes);
  60. } while (sourceBytes > 0);
  61. }
  62.  
  63. // Finish/Close arent needed strictly as the using statement does this automatically
  64.  
  65. // Finish is important to ensure trailing information for a Zip file is appended. Without this
  66. // the created file would be invalid.
  67. s.Finish();
  68.  
  69. // Close is important to wrap things up and unlock the file.
  70. s.Close();
  71. }
  72. }
  73. }
  74. }
Add Comment
Please, Sign In to add comment