C# 如何从WebAPI2HttpGet发送zip文件

C# 如何从WebAPI2HttpGet发送zip文件,c#,zipfile,ziparchive,C#,Zipfile,Ziparchive,我试图弄清楚如何从给定的文件夹路径创建新的zip文件,并将其发送回发件人 需要的是,该文件将在请求它的发件人处下载。 我已经看到了很多答案,但没有一个能帮我找到准确的答案 我的代码: Guid folderGuid=Guid.NewGuid(); 字符串folderToZip=ConfigurationManager.AppSettings[“folderToZip”]+folderGuid.ToString() CreateDirectory(folderToZip) 字符串directory

我试图弄清楚如何从给定的文件夹路径创建新的zip文件,并将其发送回发件人

需要的是,该文件将在请求它的发件人处下载。 我已经看到了很多答案,但没有一个能帮我找到准确的答案

我的代码:

Guid folderGuid=Guid.NewGuid(); 字符串folderToZip=ConfigurationManager.AppSettings[“folderToZip”]+folderGuid.ToString()

CreateDirectory(folderToZip)

字符串directoryPath=ConfigurationManager.AppSettings[“directoryPath”]; string combinedPath=Path.Combine(directoryPath,id)

DirectoryInfo di=新的DirectoryInfo(组合路径); 如果(di.存在) { //提供要创建的zip文件的路径和名称 字符串zipFile=folderToZip+“\”+folderGuid+“.zip”

在控制器中:

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:解决该文件的方法已经存在

,因此您的问题是如何创建zip文件或如何发送?如何发送。如果您要发送zip文件,可能需要使用POST命令而不是GET命令,因为GET的请求大小有限。当我使用POST时,我已使用god wierd tezt命令仅使用文件名抛出异常文件“C:******\AppData\Local\Temp\tmp96C2.tmp”已经存在。@o.Nassie我更正了代码,对此表示歉意。
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;
}