How to zip multiple files using only .net api in c#

前端 未结 9 1327
灰色年华
灰色年华 2020-12-01 09:04

I like to zip multiple files which are being created dynamically in my web application. Those files should be zipped. For this, i dont want to use any third-party tools. jus

9条回答
  •  悲哀的现实
    2020-12-01 09:39

    Well you can zip the files using following function you have to just pass the file bytes and this function will zip the file bytes passed as parameter and return the zipped file bytes.

     public static byte[] PackageDocsAsZip(byte[] fileBytesTobeZipped, string packageFileName)
    {
        try
        {
            string parentSourceLoc2Zip = @"C:\\\\UploadedDocs"\SG-ACA OCI Packages";
            if (Directory.Exists(parentSourceLoc2Zip) == false)
            {
                Directory.CreateDirectory(parentSourceLoc2Zip);
            }
    
            //if destination folder already exists then delete it
            string sourceLoc2Zip = string.Format(@"{0}\{1}", parentSourceLoc2Zip, packageFileName);
            if (Directory.Exists(sourceLoc2Zip) == true)
            {
                Directory.Delete(sourceLoc2Zip, true);
            }
            Directory.CreateDirectory(sourceLoc2Zip);
    
    
    
                 FilePath = string.Format(@"{0}\{1}",
                        sourceLoc2Zip,
                        "filename.extension");//e-g report.xlsx , report.docx according to exported file
    
                 File.WriteAllBytes(FilePath, fileBytesTobeZipped);
    
    
    
    
            //if zip already exists then delete it
            if (File.Exists(sourceLoc2Zip + ".zip"))
            {
                File.Delete(sourceLoc2Zip + ".zip");
            }
    
            //now zip the source location
            ZipFile.CreateFromDirectory(sourceLoc2Zip, sourceLoc2Zip + ".zip", System.IO.Compression.CompressionLevel.Optimal, true);
    
            return File.ReadAllBytes(sourceLoc2Zip + ".zip");
        }
        catch
        {
            throw;
        }
    }
    

    Now if you want to export this zip bytes created for user to download you can call this function using following lines

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=Report.zip");
        Response.ContentType = "application/zip";
        Response.BinaryWrite(PackageDocsAsZip(fileBytesToBeExported ,"TemporaryFolderName"));
        Response.End();
    

提交回复
热议问题