1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public static void CompressFile(string sFileToCompress, string sArchiveFile, ECompressionFormat eFormat, bool bFailOnExistOutFile)
{
Stream outCompressedStream = null;
FileStream inFileStream = null;
FileStream outFileStream = null;
FileMode outFileMode;
byte[] inBuffer;
try
{
// Read file to compress
inFileStream = new FileStream(sFileToCompress, FileMode.Open, FileAccess.Read, FileShare.Read);
inBuffer = new byte[inFileStream.Length];
inFileStream.Read(inBuffer, 0, inBuffer.Length);
// Compression
if (bFailOnExistOutFile)
outFileMode = FileMode.CreateNew;
else
outFileMode = FileMode.Create;
outFileStream = new FileStream(sArchiveFile, outFileMode, FileAccess.Write, FileShare.Read);
if (eFormat == ECompressionFormat.Gzip)
outCompressedStream = new GZipStream(outFileStream, CompressionMode.Compress);
else if (eFormat == ECompressionFormat.Deflate)
outCompressedStream = new DeflateStream(outFileStream, CompressionMode.Compress);
else
throw new ArgumentException(Resources.StrCompressInvalidFormat, "eFormat");
outCompressedStream.Write(inBuffer, 0, inBuffer.Length);
}
// catch (ArgumentNullException ex)
// {
// }
// catch (ArgumentOutOfRangeException ex)
// {
// }
// catch (ArgumentException ex)
// {
// }
// catch (FileNotFoundException ex)
// {
// }
// catch (IOException ex)
// {
// }
// catch (System.Security.SecurityException ex)
// {
// }
// catch (DirectoryNotFoundException ex)
// {
// }
// catch (UnauthorizedAccessException ex)
// {
// }
// catch (PathTooLongException ex)
// {
// }
catch (Exception ex)
{
// Failed to compress file
throw new CFileCompressorException(String.Format(Resources.StrFCompressFailed, sFileToCompress, sArchiveFile, eFormat), ex);
}
finally
{
// Close open streams
if (inFileStream != null)
inFileStream.Close();
if (outFileStream != null)
outFileStream.Close();
if (outCompressedStream != null)
outCompressedStream.Close();
}
} |
Partager