Tuesday, June 29, 2010

File Compression Or DeCompression in C#

// Posted By Suresh

//Compression
public void Compression()
{
string SourcePath = "c:\\bps.txt";
string DestPath = "c:\\bps.gz";
FileStream sourceFile = File.OpenRead(SourcePath);
FileStream destinationFile = File.Create(DestPath);
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile, CompressionMode.Compress))
{
output.Write(buffer, 0, buffer.Length);
}
// Close the files.
sourceFile.Close();
destinationFile.Close();
}


//DeCompression
public void DeCompression()
{
string SourcePath = "c:\\bps.gz";
string DestPath = "c:\\bps1.txt";
FileStream sourceFile = File.OpenRead(SourcePath);
FileStream destinationFile = File.Create(DestPath);
// Because the uncompressed size of the file is unknown,
// we are using an arbitrary buffer size.
byte[] buffer = new byte[10485760]; //10MB
int n;
using (GZipStream input = new GZipStream(sourceFile, CompressionMode.Decompress, false))
{
n = input.Read(buffer, 0, buffer.Length);
destinationFile.Write(buffer, 0, n);
}

// Close the files.
sourceFile.Close();
destinationFile.Close();
}

No comments:

Post a Comment