We interrupt this LINQ series with an emergency!
Well, there is no real emergency, but there hasn’t been a WWWTC for some time, so …
The following program is suppose to compress its own source code into a Program.cs.zip file, then reverse the compression and produce a Program.txt file.
The problem is: Program.txt always shows up as an empty file!
What’s wrong?
using System;
using System.IO;
using System.IO.Compression;
namespace YippyZippy
{
class Program
{
static void Main(string[] args)
{
Compress(@"..\..\Program.cs", @"..\..\Program.cs.zip");
Decompress(@"..\..\Program.cs.zip", @"..\..\Program.txt");
}
private static void Compress(string inFileName, string outFileName)
{
FileStream inStream = File.Open(inFileName, FileMode.Open);
FileStream outStream = File.Open(outFileName, FileMode.Create);
GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress);
try
{
byte[] buffer = new byte[inStream.Length];
inStream.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, buffer.Length);
}
finally
{
outStream.Close();
inStream.Close();
}
}
private static void Decompress(string inFileName, string outFileName)
{
FileStream input = File.Open(inFileName, FileMode.Open);
GZipStream zipStream = new GZipStream(input, CompressionMode.Decompress);
FileStream output = File.Open(outFileName, FileMode.Create);
try
{
int data = zipStream.ReadByte();
while (data > 0)
{
output.WriteByte((byte)data);
data = zipStream.ReadByte();
}
}
finally
{
output.Close();
input.Close();
}
}
}
}
Hint: You can fix the program by adding a single line of code.