Reputation: 311
Using several examples here on StackOverflow I thought the following code would decompress a gzip file then read the memory-stream and write it's content to the console. No errors occur but I get no output.
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(decompressedFileStream.Length);
decompressedFileStream.Read(memStream.GetBuffer(), 0, (int)decompressedFileStream.Length);
memStream.Position = 0;
var sr = new StreamReader(memStream);
var myStr = sr.ReadToEnd();
Console.WriteLine("Stream Output: " + myStr);
}
}
}
}
Upvotes: 0
Views: 2792
Reputation: 756
You are trying to copy an empty stream. "decompressedFileStream" is created by File.Create(), so it's empty. Swap "decompressedFileStream" to "decompressionStream" and you will be able to see your file content into "myStr".
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
MemoryStream memStream = new MemoryStream();
//memStream.SetLength(decompressedFileStream.Length); not necessary
decompressionStream.CopyTo(memStream);
memStream.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(memStream);
var myStr = sr.ReadToEnd();
Console.WriteLine("Stream Output: " + myStr);
}
}
}
}
Try this snippets. I use CopyTo instead of Read to copy the data to the memory stream and I use Seek() method instead of Position to return at the start of the memory stream.
Upvotes: 2