/// <summary> /// Attempt to extract a stream from an archive /// </summary> /// <param name="entryName">Name of the entry to be extracted</param> /// <param name="realEntry">Output representing the entry name that was found</param> /// <returns>MemoryStream representing the entry, null on error</returns> public override (MemoryStream, string) CopyToStream(string entryName) { MemoryStream ms = new MemoryStream(); string realEntry; try { // Decompress the _filename stream realEntry = Path.GetFileNameWithoutExtension(this.Filename); var xz = new XZStream(File.OpenRead(this.Filename)); // Write the file out byte[] xbuffer = new byte[_bufferSize]; int xlen; while ((xlen = xz.Read(xbuffer, 0, _bufferSize)) > 0) { ms.Write(xbuffer, 0, xlen); ms.Flush(); } // Dispose of the streams xz.Dispose(); } catch (Exception ex) { logger.Error(ex); ms = null; realEntry = null; } return(ms, realEntry); }
private static void Template(string xzFileName, string originFileName, bool useSpan) { byte[] decompDigest; byte[] originDigest; string xzFile = Path.Combine(TestSetup.SampleDir, xzFileName); string originFile = Path.Combine(TestSetup.SampleDir, originFileName); using (MemoryStream decompMs = new MemoryStream()) { XZDecompressOptions decompOpts = new XZDecompressOptions(); using (FileStream compFs = new FileStream(xzFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (XZStream xz = new XZStream(compFs, decompOpts)) { #if !NETFRAMEWORK if (useSpan) { byte[] buffer = new byte[64 * 1024]; int bytesRead; do { bytesRead = xz.Read(buffer.AsSpan()); decompMs.Write(buffer.AsSpan(0, bytesRead)); } while (0 < bytesRead); } else #endif { xz.CopyTo(decompMs); } decompMs.Flush(); xz.GetProgress(out ulong finalIn, out ulong finalOut); Assert.AreEqual(compFs.Length, xz.TotalIn); Assert.AreEqual(decompMs.Length, xz.TotalOut); Assert.AreEqual((ulong)compFs.Length, finalIn); Assert.AreEqual((ulong)decompMs.Length, finalOut); } decompMs.Position = 0; using (HashAlgorithm hash = SHA256.Create()) { decompDigest = hash.ComputeHash(decompMs); } } using (FileStream originFs = new FileStream(originFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (HashAlgorithm hash = SHA256.Create()) { originDigest = hash.ComputeHash(originFs); } } Assert.IsTrue(decompDigest.SequenceEqual(originDigest)); }