/Source/GetDotSpatial/ZipStorer.cs

# · C# · 745 lines · 457 code · 79 blank · 209 comment · 70 complexity · f62e493358f9d70911f8039b31e3d27f MD5 · raw file

  1. // ZipStorer, by Jaime Olivares
  2. // Website: zipstorer.codeplex.com
  3. // Version: 2.35 (March 14, 2010)
  4. using System.Collections.Generic;
  5. using System.Text;
  6. namespace System.IO.Compression
  7. {
  8. /// <summary>
  9. /// Unique class for compression/decompression file. Represents a Zip file.
  10. /// </summary>
  11. public class ZipStorer : IDisposable
  12. {
  13. /// <summary>
  14. /// Compression method enumeration
  15. /// </summary>
  16. public enum Compression : ushort {
  17. /// <summary>Uncompressed storage</summary>
  18. Store = 0,
  19. /// <summary>Deflate compression method</summary>
  20. Deflate = 8 }
  21. /// <summary>
  22. /// Represents an entry in Zip file directory
  23. /// </summary>
  24. public struct ZipFileEntry
  25. {
  26. /// <summary>Compression method</summary>
  27. public Compression Method;
  28. /// <summary>Full path and filename as stored in Zip</summary>
  29. public string FilenameInZip;
  30. /// <summary>Original file size</summary>
  31. public uint FileSize;
  32. /// <summary>Compressed file size</summary>
  33. public uint CompressedSize;
  34. /// <summary>Offset of header information inside Zip storage</summary>
  35. public uint HeaderOffset;
  36. /// <summary>Offset of file inside Zip storage</summary>
  37. public uint FileOffset;
  38. /// <summary>Size of header information</summary>
  39. public uint HeaderSize;
  40. /// <summary>32-bit checksum of entire file</summary>
  41. public uint Crc32;
  42. /// <summary>Last modification time of file</summary>
  43. public DateTime ModifyTime;
  44. /// <summary>User comment for file</summary>
  45. public string Comment;
  46. /// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
  47. public bool EncodeUTF8;
  48. /// <summary>Overriden method</summary>
  49. /// <returns>Filename in Zip</returns>
  50. public override string ToString()
  51. {
  52. return this.FilenameInZip;
  53. }
  54. }
  55. #region Public fields
  56. /// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
  57. public bool EncodeUTF8 = false;
  58. /// <summary>Force deflate algotithm even if it inflates the stored file. Off by default.</summary>
  59. public bool ForceDeflating = false;
  60. #endregion
  61. #region Private fields
  62. // List of files to store
  63. private List<ZipFileEntry> Files = new List<ZipFileEntry>();
  64. // Filename of storage file
  65. private string FileName;
  66. // Stream object of storage file
  67. private Stream ZipFileStream;
  68. // General comment
  69. private string Comment = "";
  70. // Central dir image
  71. private byte[] CentralDirImage = null;
  72. // Existing files in zip
  73. private ushort ExistingFiles = 0;
  74. // File access for Open method
  75. private FileAccess Access;
  76. // Static CRC32 Table
  77. private static UInt32[] CrcTable = null;
  78. // Default filename encoder
  79. private static Encoding DefaultEncoding = Encoding.GetEncoding(437);
  80. #endregion
  81. #region Public methods
  82. // Static constructor. Just invoked once in order to create the CRC32 lookup table.
  83. static ZipStorer()
  84. {
  85. // Generate CRC32 table
  86. CrcTable = new UInt32[256];
  87. for (int i = 0; i < CrcTable.Length; i++)
  88. {
  89. UInt32 c = (UInt32)i;
  90. for (int j = 0; j < 8; j++)
  91. {
  92. if ((c & 1) != 0)
  93. c = 3988292384 ^ (c >> 1);
  94. else
  95. c >>= 1;
  96. }
  97. CrcTable[i] = c;
  98. }
  99. }
  100. /// <summary>
  101. /// Method to create a new storage file
  102. /// </summary>
  103. /// <param name="_filename">Full path of Zip file to create</param>
  104. /// <param name="_comment">General comment for Zip file</param>
  105. /// <returns>A valid ZipStorer object</returns>
  106. public static ZipStorer Create(string _filename, string _comment)
  107. {
  108. Stream stream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite);
  109. ZipStorer zip = Create(stream, _comment);
  110. zip.Comment = _comment;
  111. zip.FileName = _filename;
  112. return zip;
  113. }
  114. /// <summary>
  115. /// Method to create a new zip storage in a stream
  116. /// </summary>
  117. /// <param name="_stream"></param>
  118. /// <param name="_comment"></param>
  119. /// <returns>A valid ZipStorer object</returns>
  120. public static ZipStorer Create(Stream _stream, string _comment)
  121. {
  122. ZipStorer zip = new ZipStorer();
  123. zip.Comment = _comment;
  124. zip.ZipFileStream = _stream;
  125. zip.Access = FileAccess.Write;
  126. return zip;
  127. }
  128. /// <summary>
  129. /// Method to open an existing storage file
  130. /// </summary>
  131. /// <param name="_filename">Full path of Zip file to open</param>
  132. /// <param name="_access">File access mode as used in FileStream constructor</param>
  133. /// <returns>A valid ZipStorer object</returns>
  134. public static ZipStorer Open(string _filename, FileAccess _access)
  135. {
  136. Stream stream = (Stream)new FileStream(_filename, FileMode.Open, _access == FileAccess.Read ? FileAccess.Read : FileAccess.ReadWrite);
  137. ZipStorer zip = Open(stream, _access);
  138. zip.FileName = _filename;
  139. return zip;
  140. }
  141. /// <summary>
  142. /// Method to open an existing storage from stream
  143. /// </summary>
  144. /// <param name="_stream">Already opened stream with zip contents</param>
  145. /// <param name="_access">File access mode for stream operations</param>
  146. /// <returns>A valid ZipStorer object</returns>
  147. public static ZipStorer Open(Stream _stream, FileAccess _access)
  148. {
  149. if (!_stream.CanSeek && _access != FileAccess.Read)
  150. throw new InvalidOperationException("Stream cannot seek");
  151. ZipStorer zip = new ZipStorer();
  152. //zip.FileName = _filename;
  153. zip.ZipFileStream = _stream;
  154. zip.Access = _access;
  155. if (zip.ReadFileInfo())
  156. return zip;
  157. throw new System.IO.InvalidDataException();
  158. }
  159. /// <summary>
  160. /// Add full contents of a file into the Zip storage
  161. /// </summary>
  162. /// <param name="_method">Compression method</param>
  163. /// <param name="_pathname">Full path of file to add to Zip storage</param>
  164. /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
  165. /// <param name="_comment">Comment for stored file</param>
  166. public void AddFile(Compression _method, string _pathname, string _filenameInZip, string _comment)
  167. {
  168. if (Access == FileAccess.Read)
  169. throw new InvalidOperationException("Writing is not alowed");
  170. FileStream stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read);
  171. AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment);
  172. stream.Close();
  173. }
  174. /// <summary>
  175. /// Add full contents of a stream into the Zip storage
  176. /// </summary>
  177. /// <param name="_method">Compression method</param>
  178. /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
  179. /// <param name="_source">Stream object containing the data to store in Zip</param>
  180. /// <param name="_modTime">Modification time of the data to store</param>
  181. /// <param name="_comment">Comment for stored file</param>
  182. public void AddStream(Compression _method, string _filenameInZip, Stream _source, DateTime _modTime, string _comment)
  183. {
  184. if (Access == FileAccess.Read)
  185. throw new InvalidOperationException("Writing is not alowed");
  186. long offset;
  187. if (this.Files.Count==0)
  188. offset = 0;
  189. else
  190. {
  191. ZipFileEntry last = this.Files[this.Files.Count-1];
  192. offset = last.HeaderOffset + last.HeaderSize;
  193. }
  194. // Prepare the fileinfo
  195. ZipFileEntry zfe = new ZipFileEntry();
  196. zfe.Method = _method;
  197. zfe.EncodeUTF8 = this.EncodeUTF8;
  198. zfe.FilenameInZip = NormalizedFilename(_filenameInZip);
  199. zfe.Comment = (_comment == null ? "" : _comment);
  200. // Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
  201. zfe.Crc32 = 0; // to be updated later
  202. zfe.HeaderOffset = (uint)this.ZipFileStream.Position; // offset within file of the start of this local record
  203. zfe.ModifyTime = _modTime;
  204. // Write local header
  205. WriteLocalHeader(ref zfe);
  206. zfe.FileOffset = (uint)this.ZipFileStream.Position;
  207. // Write file to zip (store)
  208. Store(ref zfe, _source);
  209. _source.Close();
  210. this.UpdateCrcAndSizes(ref zfe);
  211. Files.Add(zfe);
  212. }
  213. /// <summary>
  214. /// Updates central directory (if pertinent) and close the Zip storage
  215. /// </summary>
  216. /// <remarks>This is a required step, unless automatic dispose is used</remarks>
  217. public void Close()
  218. {
  219. if (this.Access != FileAccess.Read)
  220. {
  221. uint centralOffset = (uint)this.ZipFileStream.Position;
  222. uint centralSize = 0;
  223. if (this.CentralDirImage != null)
  224. this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length);
  225. for (int i = 0; i < Files.Count; i++)
  226. {
  227. long pos = this.ZipFileStream.Position;
  228. this.WriteCentralDirRecord(Files[i]);
  229. centralSize += (uint)(this.ZipFileStream.Position - pos);
  230. }
  231. if (this.CentralDirImage != null)
  232. this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset);
  233. else
  234. this.WriteEndRecord(centralSize, centralOffset);
  235. }
  236. if (this.ZipFileStream != null)
  237. {
  238. this.ZipFileStream.Flush();
  239. this.ZipFileStream.Dispose();
  240. this.ZipFileStream = null;
  241. }
  242. }
  243. /// <summary>
  244. /// Read all the file records in the central directory
  245. /// </summary>
  246. /// <returns>List of all entries in directory</returns>
  247. public List<ZipFileEntry> ReadCentralDir()
  248. {
  249. if (this.CentralDirImage == null)
  250. throw new InvalidOperationException("Central directory currently does not exist");
  251. List<ZipFileEntry> result = new List<ZipFileEntry>();
  252. for (int pointer = 0; pointer < this.CentralDirImage.Length; )
  253. {
  254. uint signature = BitConverter.ToUInt32(CentralDirImage, pointer);
  255. if (signature != 0x02014b50)
  256. break;
  257. bool encodeUTF8 = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) & 0x0800) != 0;
  258. ushort method = BitConverter.ToUInt16(CentralDirImage, pointer + 10);
  259. uint modifyTime = BitConverter.ToUInt32(CentralDirImage, pointer + 12);
  260. uint crc32 = BitConverter.ToUInt32(CentralDirImage, pointer + 16);
  261. uint comprSize = BitConverter.ToUInt32(CentralDirImage, pointer + 20);
  262. uint fileSize = BitConverter.ToUInt32(CentralDirImage, pointer + 24);
  263. ushort filenameSize = BitConverter.ToUInt16(CentralDirImage, pointer + 28);
  264. ushort extraSize = BitConverter.ToUInt16(CentralDirImage, pointer + 30);
  265. ushort commentSize = BitConverter.ToUInt16(CentralDirImage, pointer + 32);
  266. uint headerOffset = BitConverter.ToUInt32(CentralDirImage, pointer + 42);
  267. uint headerSize = (uint)( 46 + filenameSize + extraSize + commentSize);
  268. Encoding encoder = encodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
  269. ZipFileEntry zfe = new ZipFileEntry();
  270. zfe.Method = (Compression)method;
  271. zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize);
  272. zfe.FileOffset = GetFileOffset(headerOffset);
  273. zfe.FileSize = fileSize;
  274. zfe.CompressedSize = comprSize;
  275. zfe.HeaderOffset = headerOffset;
  276. zfe.HeaderSize = headerSize;
  277. zfe.Crc32 = crc32;
  278. zfe.ModifyTime = DosTimeToDateTime(modifyTime);
  279. if (commentSize > 0)
  280. zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize);
  281. result.Add(zfe);
  282. pointer += (46 + filenameSize + extraSize + commentSize);
  283. }
  284. return result;
  285. }
  286. /// <summary>
  287. /// Copy the contents of a stored file into a physical file
  288. /// </summary>
  289. /// <param name="_zfe">Entry information of file to extract</param>
  290. /// <param name="_filename">Name of file to store uncompressed data</param>
  291. /// <returns>True if success, false if not.</returns>
  292. /// <remarks>Unique compression methods are Store and Deflate</remarks>
  293. public bool ExtractFile(ZipFileEntry _zfe, string _filename)
  294. {
  295. // Make sure the parent directory exist
  296. string path = System.IO.Path.GetDirectoryName(_filename);
  297. if (!Directory.Exists(path))
  298. Directory.CreateDirectory(path);
  299. // Check it is directory. If so, do nothing
  300. if (Directory.Exists(_filename))
  301. return true;
  302. Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write);
  303. bool result = ExtractFile(_zfe, output);
  304. if (result)
  305. output.Close();
  306. File.SetCreationTime(_filename, _zfe.ModifyTime);
  307. File.SetLastWriteTime(_filename, _zfe.ModifyTime);
  308. return result;
  309. }
  310. /// <summary>
  311. /// Copy the contents of a stored file into an opened stream
  312. /// </summary>
  313. /// <param name="_zfe">Entry information of file to extract</param>
  314. /// <param name="_stream">Stream to store the uncompressed data</param>
  315. /// <returns>True if success, false if not.</returns>
  316. /// <remarks>Unique compression methods are Store and Deflate</remarks>
  317. public bool ExtractFile(ZipFileEntry _zfe, Stream _stream)
  318. {
  319. if (!_stream.CanWrite)
  320. throw new InvalidOperationException("Stream cannot be written");
  321. // check signature
  322. byte[] signature = new byte[4];
  323. this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin);
  324. this.ZipFileStream.Read(signature, 0, 4);
  325. if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
  326. return false;
  327. // Select input stream for inflating or just reading
  328. Stream inStream;
  329. if (_zfe.Method == Compression.Store)
  330. inStream = this.ZipFileStream;
  331. else if (_zfe.Method == Compression.Deflate)
  332. inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true);
  333. else
  334. return false;
  335. // Buffered copy
  336. byte[] buffer = new byte[16384];
  337. this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin);
  338. uint bytesPending = _zfe.FileSize;
  339. while (bytesPending > 0)
  340. {
  341. int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
  342. _stream.Write(buffer, 0, bytesRead);
  343. bytesPending -= (uint)bytesRead;
  344. }
  345. _stream.Flush();
  346. if (_zfe.Method == Compression.Deflate)
  347. inStream.Dispose();
  348. return true;
  349. }
  350. /// <summary>
  351. /// Removes one of many files in storage. It creates a new Zip file.
  352. /// </summary>
  353. /// <param name="_zip">Reference to the current Zip object</param>
  354. /// <param name="_zfes">List of Entries to remove from storage</param>
  355. /// <returns>True if success, false if not</returns>
  356. /// <remarks>This method only works for storage of type FileStream</remarks>
  357. public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes)
  358. {
  359. if (!(_zip.ZipFileStream is FileStream))
  360. throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream");
  361. //Get full list of entries
  362. List<ZipFileEntry> fullList = _zip.ReadCentralDir();
  363. //In order to delete we need to create a copy of the zip file excluding the selected items
  364. string tempZipName = Path.GetTempFileName();
  365. string tempEntryName = Path.GetTempFileName();
  366. try
  367. {
  368. ZipStorer tempZip = ZipStorer.Create(tempZipName, string.Empty);
  369. foreach (ZipFileEntry zfe in fullList)
  370. {
  371. if (!_zfes.Contains(zfe))
  372. {
  373. if (_zip.ExtractFile(zfe, tempEntryName))
  374. {
  375. tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment);
  376. }
  377. }
  378. }
  379. _zip.Close();
  380. tempZip.Close();
  381. File.Delete(_zip.FileName);
  382. File.Move(tempZipName, _zip.FileName);
  383. _zip = ZipStorer.Open(_zip.FileName, _zip.Access);
  384. }
  385. catch
  386. {
  387. return false;
  388. }
  389. finally
  390. {
  391. if (File.Exists(tempZipName))
  392. File.Delete(tempZipName);
  393. if (File.Exists(tempEntryName))
  394. File.Delete(tempEntryName);
  395. }
  396. return true;
  397. }
  398. #endregion
  399. #region Private methods
  400. // Calculate the file offset by reading the corresponding local header
  401. private uint GetFileOffset(uint _headerOffset)
  402. {
  403. byte[] buffer = new byte[2];
  404. this.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin);
  405. this.ZipFileStream.Read(buffer, 0, 2);
  406. ushort filenameSize = BitConverter.ToUInt16(buffer, 0);
  407. this.ZipFileStream.Read(buffer, 0, 2);
  408. ushort extraSize = BitConverter.ToUInt16(buffer, 0);
  409. return (uint)(30 + filenameSize + extraSize + _headerOffset);
  410. }
  411. /* Local file header:
  412. local file header signature 4 bytes (0x04034b50)
  413. version needed to extract 2 bytes
  414. general purpose bit flag 2 bytes
  415. compression method 2 bytes
  416. last mod file time 2 bytes
  417. last mod file date 2 bytes
  418. crc-32 4 bytes
  419. compressed size 4 bytes
  420. uncompressed size 4 bytes
  421. filename length 2 bytes
  422. extra field length 2 bytes
  423. filename (variable size)
  424. extra field (variable size)
  425. */
  426. private void WriteLocalHeader(ref ZipFileEntry _zfe)
  427. {
  428. long pos = this.ZipFileStream.Position;
  429. Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
  430. byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);
  431. this.ZipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0}, 0, 6); // No extra header
  432. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
  433. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
  434. this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
  435. this.ZipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later
  436. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length
  437. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
  438. this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
  439. _zfe.HeaderSize = (uint)(this.ZipFileStream.Position - pos);
  440. }
  441. /* Central directory's File header:
  442. central file header signature 4 bytes (0x02014b50)
  443. version made by 2 bytes
  444. version needed to extract 2 bytes
  445. general purpose bit flag 2 bytes
  446. compression method 2 bytes
  447. last mod file time 2 bytes
  448. last mod file date 2 bytes
  449. crc-32 4 bytes
  450. compressed size 4 bytes
  451. uncompressed size 4 bytes
  452. filename length 2 bytes
  453. extra field length 2 bytes
  454. file comment length 2 bytes
  455. disk number start 2 bytes
  456. internal file attributes 2 bytes
  457. external file attributes 4 bytes
  458. relative offset of local header 4 bytes
  459. filename (variable size)
  460. extra field (variable size)
  461. file comment (variable size)
  462. */
  463. private void WriteCentralDirRecord(ZipFileEntry _zfe)
  464. {
  465. Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
  466. byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);
  467. byte[] encodedComment = encoder.GetBytes(_zfe.Comment);
  468. this.ZipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8);
  469. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
  470. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
  471. this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
  472. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // file CRC
  473. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // compressed file size
  474. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // uncompressed file size
  475. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip
  476. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
  477. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
  478. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0
  479. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary
  480. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes
  481. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable)
  482. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4); // Offset of header
  483. this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
  484. this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
  485. }
  486. /* End of central dir record:
  487. end of central dir signature 4 bytes (0x06054b50)
  488. number of this disk 2 bytes
  489. number of the disk with the
  490. start of the central directory 2 bytes
  491. total number of entries in
  492. the central dir on this disk 2 bytes
  493. total number of entries in
  494. the central dir 2 bytes
  495. size of the central directory 4 bytes
  496. offset of start of central
  497. directory with respect to
  498. the starting disk number 4 bytes
  499. zipfile comment length 2 bytes
  500. zipfile comment (variable size)
  501. */
  502. private void WriteEndRecord(uint _size, uint _offset)
  503. {
  504. Encoding encoder = this.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
  505. byte[] encodedComment = encoder.GetBytes(this.Comment);
  506. this.ZipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8);
  507. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2);
  508. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2);
  509. this.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4);
  510. this.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4);
  511. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
  512. this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
  513. }
  514. // Copies all source file into storage file
  515. private void Store(ref ZipFileEntry _zfe, Stream _source)
  516. {
  517. byte[] buffer = new byte[16384];
  518. int bytesRead;
  519. uint totalRead = 0;
  520. Stream outStream;
  521. long posStart = this.ZipFileStream.Position;
  522. long sourceStart = _source.Position;
  523. if (_zfe.Method == Compression.Store)
  524. outStream = this.ZipFileStream;
  525. else
  526. outStream = new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true);
  527. _zfe.Crc32 = 0 ^ 0xffffffff;
  528. do
  529. {
  530. bytesRead = _source.Read(buffer, 0, buffer.Length);
  531. totalRead += (uint)bytesRead;
  532. if (bytesRead > 0)
  533. {
  534. outStream.Write(buffer, 0, bytesRead);
  535. for (uint i = 0; i < bytesRead; i++)
  536. {
  537. _zfe.Crc32 = ZipStorer.CrcTable[(_zfe.Crc32 ^ buffer[i]) & 0xFF] ^ (_zfe.Crc32 >> 8);
  538. }
  539. }
  540. } while (bytesRead == buffer.Length);
  541. outStream.Flush();
  542. if (_zfe.Method == Compression.Deflate)
  543. outStream.Dispose();
  544. _zfe.Crc32 ^= 0xffffffff;
  545. _zfe.FileSize = totalRead;
  546. _zfe.CompressedSize = (uint)(this.ZipFileStream.Position - posStart);
  547. // Verify for real compression
  548. if (_zfe.Method == Compression.Deflate && !this.ForceDeflating && _source.CanSeek && _zfe.CompressedSize > _zfe.FileSize)
  549. {
  550. // Start operation again with Store algorithm
  551. _zfe.Method = Compression.Store;
  552. this.ZipFileStream.Position = posStart;
  553. this.ZipFileStream.SetLength(posStart);
  554. _source.Position = sourceStart;
  555. this.Store(ref _zfe, _source);
  556. }
  557. }
  558. /* DOS Date and time:
  559. MS-DOS date. The date is a packed value with the following format. Bits Description
  560. 0-4 Day of the month (1&#x2013;31)
  561. 5-8 Month (1 = January, 2 = February, and so on)
  562. 9-15 Year offset from 1980 (add 1980 to get actual year)
  563. MS-DOS time. The time is a packed value with the following format. Bits Description
  564. 0-4 Second divided by 2
  565. 5-10 Minute (0&#x2013;59)
  566. 11-15 Hour (0&#x2013;23 on a 24-hour clock)
  567. */
  568. private uint DateTimeToDosTime(DateTime _dt)
  569. {
  570. return (uint)(
  571. (_dt.Second / 2) | (_dt.Minute << 5) | (_dt.Hour << 11) |
  572. (_dt.Day<<16) | (_dt.Month << 21) | ((_dt.Year - 1980) << 25));
  573. }
  574. private DateTime DosTimeToDateTime(uint _dt)
  575. {
  576. return new DateTime(
  577. (int)(_dt >> 25) + 1980,
  578. (int)(_dt >> 21) & 15,
  579. (int)(_dt >> 16) & 31,
  580. (int)(_dt >> 11) & 31,
  581. (int)(_dt >> 5) & 63,
  582. (int)(_dt & 31) * 2);
  583. }
  584. /* CRC32 algorithm
  585. The 'magic number' for the CRC is 0xdebb20e3.
  586. The proper CRC pre and post conditioning
  587. is used, meaning that the CRC register is
  588. pre-conditioned with all ones (a starting value
  589. of 0xffffffff) and the value is post-conditioned by
  590. taking the one's complement of the CRC residual.
  591. If bit 3 of the general purpose flag is set, this
  592. field is set to zero in the local header and the correct
  593. value is put in the data descriptor and in the central
  594. directory.
  595. */
  596. private void UpdateCrcAndSizes(ref ZipFileEntry _zfe)
  597. {
  598. long lastPos = this.ZipFileStream.Position; // remember position
  599. this.ZipFileStream.Position = _zfe.HeaderOffset + 8;
  600. this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method
  601. this.ZipFileStream.Position = _zfe.HeaderOffset + 14;
  602. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // Update CRC
  603. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // Compressed size
  604. this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // Uncompressed size
  605. this.ZipFileStream.Position = lastPos; // restore position
  606. }
  607. // Replaces backslashes with slashes to store in zip header
  608. private string NormalizedFilename(string _filename)
  609. {
  610. string filename = _filename.Replace('\\', '/');
  611. int pos = filename.IndexOf(':');
  612. if (pos >= 0)
  613. filename = filename.Remove(0, pos + 1);
  614. return filename.Trim('/');
  615. }
  616. // Reads the end-of-central-directory record
  617. private bool ReadFileInfo()
  618. {
  619. if (this.ZipFileStream.Length < 22)
  620. return false;
  621. try
  622. {
  623. this.ZipFileStream.Seek(-17, SeekOrigin.End);
  624. BinaryReader br = new BinaryReader(this.ZipFileStream);
  625. do
  626. {
  627. this.ZipFileStream.Seek(-5, SeekOrigin.Current);
  628. UInt32 sig = br.ReadUInt32();
  629. if (sig == 0x06054b50)
  630. {
  631. this.ZipFileStream.Seek(6, SeekOrigin.Current);
  632. UInt16 entries = br.ReadUInt16();
  633. Int32 centralSize = br.ReadInt32();
  634. UInt32 centralDirOffset = br.ReadUInt32();
  635. UInt16 commentSize = br.ReadUInt16();
  636. // check if comment field is the very last data in file
  637. if (this.ZipFileStream.Position + commentSize != this.ZipFileStream.Length)
  638. return false;
  639. // Copy entire central directory to a memory buffer
  640. this.ExistingFiles = entries;
  641. this.CentralDirImage = new byte[centralSize];
  642. this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
  643. this.ZipFileStream.Read(this.CentralDirImage, 0, centralSize);
  644. // Leave the pointer at the begining of central dir, to append new files
  645. this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
  646. return true;
  647. }
  648. } while (this.ZipFileStream.Position > 0);
  649. }
  650. catch { }
  651. return false;
  652. }
  653. #endregion
  654. #region IDisposable Members
  655. /// <summary>
  656. /// Closes the Zip file stream
  657. /// </summary>
  658. public void Dispose()
  659. {
  660. this.Close();
  661. }
  662. #endregion
  663. }
  664. }