ZipHandler.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Linq;
  5. using Xilium.CefGlue.Common.Handlers;
  6. namespace fis.Win.Handlers
  7. {
  8. internal class ZipHandler : IHostHandler, IDisposable
  9. {
  10. private readonly string _fileName = string.Empty;
  11. private readonly ZipArchive _archive;
  12. private bool _disposed;
  13. public string Host { get; }
  14. public ZipHandler(string host, string zipFile)
  15. {
  16. Host = host;
  17. if (File.Exists(zipFile))
  18. {
  19. _fileName = Path.GetFileNameWithoutExtension(zipFile);
  20. }
  21. _archive = ZipFile.Open(zipFile, ZipArchiveMode.Read);
  22. }
  23. ~ZipHandler()
  24. {
  25. Dispose();
  26. }
  27. public HandleResult Handle(string path, byte[] postData = null)
  28. {
  29. try
  30. {
  31. string text = path;
  32. if (text.StartsWith("/"))
  33. {
  34. text = text.Substring(1);
  35. }
  36. string path2 = _fileName + "/" + text;
  37. var entry = _archive.Entries.FirstOrDefault(x => x.FullName == path2);
  38. if(entry != null)
  39. {
  40. string mimeType = MimeTypeMap.GetMimeType(Path.GetExtension(path2)!.ToLower());
  41. using (var entryStream = entry.Open())
  42. {
  43. var ms = new MemoryStream();
  44. entryStream.CopyTo(ms);
  45. return new HandleResult(ms, mimeType);
  46. }
  47. }
  48. if (File.Exists(path2))
  49. {
  50. }
  51. }
  52. catch
  53. {
  54. }
  55. return null;
  56. }
  57. private void DoDispose()
  58. {
  59. if (!_disposed)
  60. {
  61. _archive.Dispose();
  62. _disposed = true;
  63. }
  64. }
  65. public void Dispose()
  66. {
  67. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  68. DoDispose();
  69. GC.SuppressFinalize(this);
  70. }
  71. }
  72. }