Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ZipPackage.cs 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml;
  8. using DocX.iOS.Zip;
  9. namespace System.IO.Packaging
  10. {
  11. class UriComparer : IEqualityComparer<Uri>
  12. {
  13. public int GetHashCode(Uri uri)
  14. {
  15. return 1;
  16. }
  17. public bool Equals(Uri x, Uri y)
  18. {
  19. return x.OriginalString.Equals(y.OriginalString, StringComparison.OrdinalIgnoreCase);
  20. }
  21. }
  22. public sealed class ZipPackage : Package
  23. {
  24. public ZipStorer Archive { get; set; }
  25. private const string ContentNamespace = "http://schemas.openxmlformats.org/package/2006/content-types";
  26. private const string ContentUri = "[Content_Types].xml";
  27. bool OwnsStream
  28. {
  29. get;
  30. set;
  31. }
  32. Dictionary<Uri, ZipPackagePart> parts;
  33. internal Dictionary<Uri, MemoryStream> PartStreams = new Dictionary<Uri, MemoryStream>(new UriComparer());
  34. internal Stream PackageStream { get; set; }
  35. Dictionary<Uri, ZipPackagePart> Parts
  36. {
  37. get
  38. {
  39. if (parts == null)
  40. LoadParts();
  41. return parts;
  42. }
  43. }
  44. internal ZipPackage(FileAccess access, bool ownsStream, Stream stream)
  45. : base(access)
  46. {
  47. OwnsStream = ownsStream;
  48. PackageStream = stream;
  49. }
  50. internal ZipPackage(FileAccess access, bool ownsStream, Stream stream, bool streaming)
  51. : base(access, streaming)
  52. {
  53. OwnsStream = ownsStream;
  54. PackageStream = stream;
  55. }
  56. protected override void Dispose(bool disposing)
  57. {
  58. foreach (Stream s in PartStreams.Values)
  59. s.Close();
  60. if (Archive != null) // GZE fixed bug where Archive == null
  61. {
  62. Archive.Close();
  63. }
  64. base.Dispose(disposing);
  65. if (OwnsStream)
  66. PackageStream.Close();
  67. }
  68. protected override void FlushCore()
  69. {
  70. // Ensure that all the data has been read out of the package
  71. // stream already. Otherwise we'll lose data when we recreate the zip
  72. foreach (ZipPackagePart part in Parts.Values)
  73. {
  74. part.GetStream();
  75. }
  76. if (!PackageStream.CanSeek)
  77. return;
  78. // Empty the package stream
  79. PackageStream.Position = 0;
  80. PackageStream.SetLength(0);
  81. // Recreate the zip file
  82. using (ZipStorer archive = ZipStorer.Create(PackageStream, "", false))
  83. {
  84. // Write all the part streams
  85. foreach (ZipPackagePart part in Parts.Values)
  86. {
  87. Stream partStream = part.GetStream();
  88. partStream.Seek(0, SeekOrigin.Begin);
  89. archive.AddStream(ZipStorer.Compression.Deflate, part.Uri.ToString().Substring(1), partStream,
  90. DateTime.UtcNow, "");
  91. }
  92. using (var ms = new MemoryStream())
  93. {
  94. WriteContentType(ms);
  95. ms.Seek(0, SeekOrigin.Begin);
  96. archive.AddStream(ZipStorer.Compression.Deflate, ContentUri, ms, DateTime.UtcNow, "");
  97. }
  98. }
  99. }
  100. protected override PackagePart CreatePartCore(Uri partUri, string contentType, CompressionOption compressionOption)
  101. {
  102. ZipPackagePart part = new ZipPackagePart(this, partUri, contentType, compressionOption);
  103. Parts.Add(part.Uri, part);
  104. return part;
  105. }
  106. protected override void DeletePartCore(Uri partUri)
  107. {
  108. Parts.Remove(partUri);
  109. }
  110. protected override PackagePart GetPartCore(Uri partUri)
  111. {
  112. ZipPackagePart part;
  113. Parts.TryGetValue(partUri, out part);
  114. return part;
  115. }
  116. protected override PackagePart[] GetPartsCore()
  117. {
  118. ZipPackagePart[] p = new ZipPackagePart[Parts.Count];
  119. Parts.Values.CopyTo(p, 0);
  120. return p;
  121. }
  122. void LoadParts()
  123. {
  124. parts = new Dictionary<Uri, ZipPackagePart>(new UriComparer());
  125. try
  126. {
  127. PackageStream.Seek(0, SeekOrigin.Begin);
  128. if (Archive == null)
  129. {
  130. Archive = ZipStorer.Open(PackageStream, FileAccess.Read, false);
  131. }
  132. List<ZipStorer.ZipFileEntry> dir = Archive.ReadCentralDir();
  133. // Load the content type map file
  134. XmlDocument doc = new XmlDocument();
  135. var content = dir.FirstOrDefault(x => x.FilenameInZip == ContentUri);
  136. using (var ms = new MemoryStream())
  137. {
  138. Archive.ExtractFile(content, ms);
  139. ms.Seek(0, SeekOrigin.Begin);
  140. doc.Load(ms);
  141. }
  142. XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
  143. manager.AddNamespace("content", ContentNamespace);
  144. // The file names in the zip archive are not prepended with '/'
  145. foreach (var file in dir)
  146. {
  147. if (file.FilenameInZip.Equals(ContentUri, StringComparison.Ordinal))
  148. continue;
  149. XmlNode node;
  150. if (file.FilenameInZip == RelationshipUri.ToString().Substring(1))
  151. {
  152. CreatePartCore(RelationshipUri, RelationshipContentType, CompressionOption.Normal);
  153. continue;
  154. }
  155. string xPath = string.Format("/content:Types/content:Override[@PartName='/{0}']", file);
  156. node = doc.SelectSingleNode(xPath, manager);
  157. if (node == null)
  158. {
  159. string ext = Path.GetExtension(file.FilenameInZip);
  160. if (ext.StartsWith("."))
  161. ext = ext.Substring(1);
  162. xPath = string.Format("/content:Types/content:Default[@Extension='{0}']", ext);
  163. node = doc.SelectSingleNode(xPath, manager);
  164. }
  165. // What do i do if the node is null? This means some has tampered with the
  166. // package file manually
  167. if (node != null)
  168. CreatePartCore(new Uri("/" + file, UriKind.Relative), node.Attributes["ContentType"].Value,
  169. CompressionOption.Normal);
  170. }
  171. }
  172. catch
  173. {
  174. // The archive is invalid - therefore no parts
  175. }
  176. }
  177. void WriteContentType(Stream s)
  178. {
  179. XmlDocument doc = new XmlDocument();
  180. XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
  181. Dictionary<string, string> mimes = new Dictionary<string, string>();
  182. manager.AddNamespace("content", ContentNamespace);
  183. doc.AppendChild(doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""));
  184. XmlNode root = doc.CreateNode(XmlNodeType.Element, "Types", ContentNamespace);
  185. doc.AppendChild(root);
  186. foreach (ZipPackagePart part in Parts.Values)
  187. {
  188. XmlNode node = null;
  189. string existingMimeType;
  190. var extension = Path.GetExtension(part.Uri.OriginalString);
  191. if (extension.Length > 0)
  192. extension = extension.Substring(1);
  193. if (!mimes.TryGetValue(extension, out existingMimeType))
  194. {
  195. node = doc.CreateNode(XmlNodeType.Element, "Default", ContentNamespace);
  196. XmlAttribute ext = doc.CreateAttribute("Extension");
  197. ext.Value = extension;
  198. node.Attributes.Append(ext);
  199. mimes[extension] = part.ContentType;
  200. }
  201. else if (part.ContentType != existingMimeType)
  202. {
  203. node = doc.CreateNode(XmlNodeType.Element, "Override", ContentNamespace);
  204. XmlAttribute name = doc.CreateAttribute("PartName");
  205. name.Value = part.Uri.ToString();
  206. node.Attributes.Append(name);
  207. }
  208. if (node != null)
  209. {
  210. XmlAttribute contentType = doc.CreateAttribute("ContentType");
  211. contentType.Value = part.ContentType;
  212. node.Attributes.Prepend(contentType);
  213. root.AppendChild(node);
  214. }
  215. }
  216. XmlTextWriter writer = new XmlTextWriter(s, System.Text.Encoding.UTF8);
  217. doc.WriteTo(writer);
  218. writer.Flush();
  219. }
  220. }
  221. }