2

I'm trying to figure it out how to create new zip file from a given folder path, and sending it back to the sender.

The need is that the file will be downloaded at the sender that requested it. I've seen alot of answers but none helped me with the exact answer.

My code:

Guid folderGuid = Guid.NewGuid(); string folderToZip = ConfigurationManager.AppSettings["folderToZip"] + folderGuid.ToString();

Directory.CreateDirectory(folderToZip);

string directoryPath = ConfigurationManager.AppSettings["DirectoryPath"]; string combinedPath = Path.Combine(directoryPath, id);

DirectoryInfo di = new DirectoryInfo(combinedPath); if (di.Exists) { //provide the path and name for the zip file to create string zipFile = folderToZip + "\" + folderGuid + ".zip";

//call the ZipFile.CreateFromDirectory() method
ZipFile.CreateFromDirectory(combinedPath, zipFile, CompressionLevel.Fastest, true);

var result = new HttpResponseMessage(HttpStatusCode.OK);
using (ZipArchive zip = ZipFile.Open(zipFile, ZipArchiveMode.Read))
{
    zip.CreateEntryFromFile(folderFiles, "file.zip");
}

var stream = new FileStream(zipFile, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "file.zip"
};
log.Debug("END ExportFiles()");
return ResponseMessage(result);
zx485
  • 28,498
  • 28
  • 50
  • 59
o.Nassie
  • 133
  • 1
  • 2
  • 8

1 Answers1

7

In your controller:

using System.IO.Compression.FileSystem; // Reference System.IO.Compression.FileSystem.dll

[HttpGet]
[Route("api/myzipfile"]
public dynamic DownloadZip([FromUri]string dirPath)
{
if(!System.IO.Directory.Exists(dirPath))
   return this.NotFound();

    var tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid()); // might want to clean this up if there are a lot of downloads
    ZipFile.CreateFromDirectory(dirPath, tempFile);
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(tempFile, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");

  return response;
}

UPD: Workaround the File Already Exists

zaitsman
  • 8,984
  • 6
  • 47
  • 79