Skip to content

Instantly share code, notes, and snippets.

@piksel
Created February 1, 2020 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piksel/7ade2571713b992e4c532a93385067f8 to your computer and use it in GitHub Desktop.
Save piksel/7ade2571713b992e4c532a93385067f8 to your computer and use it in GitHub Desktop.
Solution to SharpZipLib issue #413
using ICSharpCode.SharpZipLib.BZip2;
using System;
using System.Diagnostics;
using System.IO;
namespace Issue413
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("SharpZipLib Issue 413\n");
var sw = new Stopwatch();
Console.WriteLine("Decompressing WITHOUT MultiStreams:");
sw.Start();
DecompressBZ2File(false, "naxos_US_2019-07-07-noMS.txt");
sw.Stop();
Console.WriteLine($" Decompression time: {sw.ElapsedMilliseconds/1000.0:f3}s");
Console.WriteLine();
Console.WriteLine("Decompressing WITH MultiStreams:");
sw.Restart();
DecompressBZ2File(true, "naxos_US_2019-07-07-MS.txt");
sw.Stop();
Console.WriteLine($" Decompression time: {sw.ElapsedMilliseconds / 1000.0:f3}s");
}
private static void DecompressBZ2File(bool multiStream, string txtFilePath)
{
string bz2FilePath = $"naxos_US_2019-07-07.txt.bz2";
FileInfo zipFileName = new FileInfo(bz2FilePath);
using (FileStream fileToDecompressAsStream = zipFileName.OpenRead())
{
using (FileStream decompressedStream = File.Create(txtFilePath))
{
try
{
Bzip2_Decompress(fileToDecompressAsStream, decompressedStream, true, multiStream);
Console.WriteLine(" Successfully decompressed BZ2 file.");
}
catch (Exception ex)
{
Console.WriteLine($" Error decompressing: {ex.GetType().Name}: {ex.Message}");
Console.WriteLine($" {ex.StackTrace.Replace("\n", "\n ")}");
}
}
}
using var fs = File.OpenRead(txtFilePath);
using var sr = new StreamReader(fs);
var lines = 0L;
while (sr.ReadLine() is string) lines++;
Console.WriteLine($" Output file size: {fs.Length} byte(s) ({lines} line(s))");
}
public static void Bzip2_Decompress(Stream inStream, Stream outStream, bool isStreamOwner, bool tryMultiStream)
{
if (inStream == null)
{
throw new ArgumentNullException(nameof(inStream));
}
if (outStream == null)
{
throw new ArgumentNullException(nameof(outStream));
}
try
{
long posBeforeRead;
long bytesLeft;
long bytesRead;
do
{
posBeforeRead = inStream.Position;
using (BZip2InputStream bzipInput = new BZip2InputStream(inStream))
{
bzipInput.IsStreamOwner = false;
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(bzipInput, outStream, new byte[4096]);
}
bytesRead = inStream.Position - posBeforeRead;
bytesLeft = inStream.Length - inStream.Position;
} while (tryMultiStream && bytesRead > 0 && bytesLeft > 0);
}
finally
{
if (isStreamOwner)
{
inStream.Dispose();
outStream.Dispose();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment