简体   繁体   English

如何使用C#将Excel文件压缩为zip或cap文件扩展名

[英]How to compress a Excel file to zip or cap file extention using C#

I want to compress a Excel file to .zip or .cap extension. 我想将Excel文件压缩为.zip或.cap扩展名。 The code Used to do that it is compressing the file but that zip file can't be unzip. 用于执行此操作的代码正在压缩文件,但该zip文件无法解压缩。 while unzip that i am getting the error file file corrupted or can't be unzip. 解压缩时,我得到的错误文件文件已损坏或无法解压缩。 The code I am using: 我正在使用的代码:

    static public bool CompressFile(string file, string outputFile)

      {

        try
        {

            using (var inFile = File.OpenRead(file))
            {

                using (var outFile = File.Create(outputFile))
                {

                    using (var compress = new GZipStream(outFile, CompressionMode.Compress, false))
                    {

                        byte[] buffer = new byte[inFile.Length];


                        int read = inFile.Read(buffer, 0, buffer.Length);

                        while (read > 0)
                        {
                            compress.Write(buffer, 0, read);
                            read = inFile.Read(buffer, 0, buffer.Length);
                        }
                    }
                }
            }
            return true;
        }
        catch (IOException ex)
        {
       MessageBox.Show(string.Format("Error compressing file: {0}", ex.Message));
            return false;
        }
    }

Even i go some link to get the proper solution. 即使我去一些链接,以获取适当的解决方案。 But nothing is workout.I need some suggestion to get the proper solution. 但是什么都不是锻炼。我需要一些建议以获得正确的解决方案。 Any answer please. 请回答。

This code uses the SharpZipLib library and will compress files that can be uncompressed no problems 此代码使用SharpZipLib库,将压缩可以解压缩的文件没有问题

    private void Zip()
    {
        string output = @"C:\TEMP\test.zip";
        string input = @"C:\TEMP\test.xlsx";

        using (var zipStream = new ZipOutputStream(System.IO.File.Create(output)))
        {
            zipStream.SetLevel(9);
            var buffer = new byte[4096];
            var entry = new ZipEntry(Path.GetFileName(input));
            zipStream.PutNextEntry(entry);

            using (FileStream fs = System.IO.File.OpenRead(input))
            {
                int sourceBytes;
                do
                {
                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                    zipStream.Write(buffer, 0, sourceBytes);
                } while (sourceBytes > 0);
            }

            zipStream.Finish();
            zipStream.Close();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM