IWritableArchiveExtensions.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #if !NO_FILE
  2. using System;
  3. #endif
  4. using System.IO;
  5. using SharpCompress.Writers;
  6. namespace SharpCompress.Archives
  7. {
  8. public static class IWritableArchiveExtensions
  9. {
  10. #if !NO_FILE
  11. public static void AddEntry(this IWritableArchive writableArchive,
  12. string entryPath, string filePath)
  13. {
  14. var fileInfo = new FileInfo(filePath);
  15. if (!fileInfo.Exists)
  16. {
  17. throw new FileNotFoundException("Could not AddEntry: " + filePath);
  18. }
  19. writableArchive.AddEntry(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length,
  20. fileInfo.LastWriteTime);
  21. }
  22. public static void SaveTo(this IWritableArchive writableArchive, string filePath, WriterOptions options)
  23. {
  24. writableArchive.SaveTo(new FileInfo(filePath), options);
  25. }
  26. public static void SaveTo(this IWritableArchive writableArchive, FileInfo fileInfo, WriterOptions options)
  27. {
  28. using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write))
  29. {
  30. writableArchive.SaveTo(stream, options);
  31. }
  32. }
  33. public static void AddAllFromDirectory(
  34. this IWritableArchive writableArchive,
  35. string filePath, string searchPattern = "*.*", SearchOption searchOption = SearchOption.AllDirectories)
  36. {
  37. #if NET35
  38. foreach (var path in Directory.GetFiles(filePath, searchPattern, searchOption))
  39. #else
  40. foreach (var path in Directory.EnumerateFiles(filePath, searchPattern, searchOption))
  41. #endif
  42. {
  43. var fileInfo = new FileInfo(path);
  44. writableArchive.AddEntry(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length,
  45. fileInfo.LastWriteTime);
  46. }
  47. }
  48. public static IArchiveEntry AddEntry(this IWritableArchive writableArchive, string key, FileInfo fileInfo)
  49. {
  50. if (!fileInfo.Exists)
  51. {
  52. throw new ArgumentException("FileInfo does not exist.");
  53. }
  54. return writableArchive.AddEntry(key, fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime);
  55. }
  56. #endif
  57. }
  58. }