简体   繁体   中英

C# MVC WebService - Zip a file and return it

I have an MVC C# webservice and I need to have a string converted into a zip file with a specific name and return it.

I have assembled this code from various StackOverFlow posts but certain keywords are not recognized (ZipFile,CreateEntryFromFile) while others do (ZipArchive)

string xmlReply = "This is a test";


        //Convert to bytes and encode to Base64
        Byte[] bytes = File.ReadAllBytes(xmlReply);

        //Write it back to string
        xmlReply = Convert.ToBase64String(bytes);

        //Write string to file
        string filename = @"C:\Users\Public\tr_file";
        System.IO.File.WriteAllText(filename, xmlReply);

        string fileNameZip = @"C:\Users\Public\FileR.zip";

        //Zip
        using (ZipArchive zip = ZipFile.Open(fileNameZip, ZipArchiveMode.Create))
        {
            zip.CreateEntryFromFile(filename, Path.GetFileName(filename));
        }

        //Break zip into bytes and return it
        byte[] fileBytes = System.IO.File.ReadAllBytes(fileNameZip);
        return new FileContentResult(fileBytes, "application/zip");

Can you help pointing out the errors or suggesting anoher way to achieve it?

Thanx

EDIT : For the missing keywords I found that I needed to add a Reference to System.IO.Compression.FileSystem

Will the FileContentResult do the trick and return the zip?

Your code looks almost exactly like the example on this page

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string zipPath = @"c:\users\exampleuser\start.zip";
            string extractPath = @"c:\users\exampleuser\extract";
            string newFile = @"c:\users\exampleuser\NewFile.txt";

            using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
            {
                 archive.CreateEntryFromFile(newFile, "NewEntry.txt");
                 archive.ExtractToDirectory(extractPath);
            } 
        }
    }
} 

Add :

  using System.IO.Compression;

And if it doesn't work, check if your target framework is at least at 4.5.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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