Posted By

kyrathaba on 01/24/11


Tagged

archive zip compression


Versions (?)

Creating and reading from zip file


 / Published in: C#
 

credit goes to Jaime Olivares of codeplex.com

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

Report this snippet  

You need to login to post a comment.