TarHeaderFactory.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using SharpCompress.Common.Tar.Headers;
  4. using SharpCompress.IO;
  5. using System.Text;
  6. namespace SharpCompress.Common.Tar
  7. {
  8. internal static class TarHeaderFactory
  9. {
  10. internal static IEnumerable<TarHeader> ReadHeader(StreamingMode mode, Stream stream, ArchiveEncoding archiveEncoding)
  11. {
  12. while (true)
  13. {
  14. TarHeader header = null;
  15. try
  16. {
  17. BinaryReader reader = new BinaryReader(stream);
  18. header = new TarHeader(archiveEncoding);
  19. if (!header.Read(reader))
  20. {
  21. yield break;
  22. }
  23. switch (mode)
  24. {
  25. case StreamingMode.Seekable:
  26. {
  27. header.DataStartPosition = reader.BaseStream.Position;
  28. //skip to nearest 512
  29. reader.BaseStream.Position += PadTo512(header.Size);
  30. }
  31. break;
  32. case StreamingMode.Streaming:
  33. {
  34. header.PackedStream = new TarReadOnlySubStream(stream, header.Size);
  35. }
  36. break;
  37. default:
  38. {
  39. throw new InvalidFormatException("Invalid StreamingMode");
  40. }
  41. }
  42. }
  43. catch
  44. {
  45. header = null;
  46. }
  47. yield return header;
  48. }
  49. }
  50. private static long PadTo512(long size)
  51. {
  52. int zeros = (int)(size % 512);
  53. if (zeros == 0)
  54. {
  55. return size;
  56. }
  57. return 512 - zeros + size;
  58. }
  59. }
  60. }