VS2010 C# 壓縮/解壓 單一檔案(範例2)『C# GZipStream』
VS2010 C# 壓縮/解壓 單一檔案(範例2)『C# GZipStream』
//壓縮
protected void Compress_Click1(object sender, EventArgs e)
{
//己經有確定要壓縮的檔案
FileStream sourceFile = File.OpenRead(@”C:\sample.xml”);
//壓縮後的檔案名稱
FileStream destFile = File.Create(@”C:\sample.gz”);
//開始
GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress, true);
try
{
int theByte = sourceFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = sourceFile.ReadByte();
}
}
finally
{
compStream.Flush();
compStream.Dispose();
sourceFile.Flush();
sourceFile.Dispose();
destFile.Flush();
destFile.Dispose();
}
}
//解壓縮
protected void Decompress_Click(object sender, EventArgs e)
{
//被壓縮後的檔案
FileStream sourceFile = File.OpenRead(@”C:\sample.gz”);
//解壓縮後的檔案
FileStream destFile = File.Create(@”C:\Unsample.xml”);
//開始
GZipStream compStream = new GZipStream(sourceFile, CompressionMode.Decompress, true);
try
{
int theByte = compStream.ReadByte();
while (theByte != -1)
{
destFile.WriteByte((byte)theByte);
theByte = compStream.ReadByte();
}
}
finally
{
compStream.Flush();
compStream.Dispose();
sourceFile.Flush();
sourceFile.Dispose();
destFile.Flush();
destFile.Dispose();
}
}