Would you like to react to this message? Create an account in a few clicks or log in to continue.

    My Backup - Compress GZIP

    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    My Backup - Compress GZIP Empty My Backup - Compress GZIP

    Post  Admin Thu Nov 26, 2009 8:36 am

    Your C# code file should have the following using statements:
    using System.IO;
    using System.IO.Compression;
    using System.Text;

    Here are sample functions to compress and decompress a file:

    Code:
    private void TestCompress()
    {
        string srcFile = "C:\\temp\\file-to-compress.txt";
        string dstFile = "C:\\temp\\compressed-file.gzip";

        FileStream fsIn = null; // will open and read the srcFile
        FileStream fsOut = null; // will be used by the GZipStream for output to the dstFile
        GZipStream gzip = null;
        byte[] buffer;
        int count = 0;

        try
        {
            fsOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
            gzip = new GZipStream(fsOut, CompressionMode.Compress, true);

            fsIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            buffer = new byte[fsIn.Length];
            count = fsIn.Read(buffer, 0, buffer.Length);
            fsIn.Close();
            fsIn = null;

            // compress to the destination file
            gzip.Write(buffer, 0, buffer.Length);
        }
        catch (Exception ex)
        {
            // handle or display the error
            System.Diagnostics.Debug.Assert(false, ex.ToString());
        }
        finally
        {
            if (gzip != null)
            {
                gzip.Close();
                gzip = null;
            }
            if (fsOut != null)
            {
                fsOut.Close();
                fsOut = null;
            }
            if (fsIn != null)
            {
                fsIn.Close();
                fsIn = null;
            }
        }
    }

      Current date/time is Mon May 20, 2024 11:42 am