(原創)檔案壓縮代碼
來源:互聯網
上載者:User
#region 檔案壓縮
/// <summary>
/// 檔案壓縮
/// </summary>
/// <param name="M_str_DFile">壓縮前檔案及路徑</param>
/// <param name="M_str_CFile">壓縮後檔案及路徑</param>
public void compressFile(string M_str_DFile, string M_str_CFile)
{
if (!File.Exists(M_str_DFile)) throw new FileNotFoundException();
using (FileStream sourceStream = new FileStream(M_str_DFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
byte[] buffer = new byte[sourceStream.Length];
int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);
if (checkCounter != buffer.Length) throw new ApplicationException();
using (FileStream destinationStream = new FileStream(M_str_CFile, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true))
{
compressedStream.Write(buffer, 0, buffer.Length);
}
}
}
}