Compressor.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.IO.Compression;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. namespace Universal;
  5. public class Compressor
  6. {
  7. public static bool CompressZipFileDirectory(DirectoryInfo sourceDirectory, DirectoryInfo zipFilePath, string fileName, out string? fullZippedPath)
  8. {
  9. fullZippedPath = null;
  10. if (!sourceDirectory.Exists)
  11. return false;
  12. if (string.IsNullOrEmpty(fileName))
  13. return false;
  14. if (!fileName.EndsWith(".zip"))
  15. fileName = $"{fileName}.zip";
  16. fullZippedPath = Path.Combine(zipFilePath.FullName, fileName);
  17. try
  18. {
  19. ZipFile.CreateFromDirectory(sourceDirectory.FullName, fullZippedPath, CompressionLevel.SmallestSize, false);
  20. }
  21. catch
  22. {
  23. return false;
  24. }
  25. return true;
  26. }
  27. public static bool CompressZipFileDirectory(DirectoryInfo sourceDirectory, Stream stream)
  28. {
  29. if (!sourceDirectory.Exists)
  30. return false;
  31. try
  32. {
  33. ZipFile.CreateFromDirectory(sourceDirectory.FullName, stream, CompressionLevel.SmallestSize, false);
  34. }
  35. catch
  36. {
  37. return false;
  38. }
  39. return true;
  40. }
  41. public static bool DecompressZipFile(string path, Stream stream)
  42. {
  43. try
  44. {
  45. DirectoryInfo directory = new(path);
  46. if (!directory.Exists)
  47. directory.Create();
  48. ZipFile.ExtractToDirectory(stream, path, true);
  49. }
  50. catch
  51. {
  52. return false;
  53. }
  54. return true;
  55. }
  56. }