C# IFormFile 作为 ZipFile

Rom*_*ets 0 c# zipfile iformfile asp.net-core-1.1 .net-standard

我有一个 REST API 端点,它在 .Net Core 1.1 上接收 zip 文件。我从这样的请求中获取 IFormFile

var zipFile = HttpContext.Request.Form.Files.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

然后我需要将它传递给不支持 IFormFile 的 .Net Standard 1.5 中的 service 方法。

所以问题是:如何将 IFormFile 转换为 ZipFile 或标准 1.5 支持的其他类型,或者可能有一些更合适的方法来操作 zip 文件?谢谢!

pok*_*oke 7

IFormFile只是接收文件的包装器。你仍然应该阅读实际文件做一些事情。例如,您可以将文件流读入一个字节数组并将其传递给服务:

byte[] fileData;
using (var stream = new MemoryStream((int)file.Length))
{
    file.CopyTo(stream);
    fileData = stream.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

或者您可以将流复制到文件系统中的物理文件中。

但这基本上取决于您实际想要对上传的文件做什么,因此您应该从那个方向开始并将其转换IFormFile为您需要的东西。


如果您想以 ZIP 格式打开文件并从中提取某些内容,您可以尝试使用流的ZipArchive构造函数。像这样的东西:

using (var stream = file.OpenReadStream())
using (var archive = new ZipArchive(stream))
{
    var innerFile = archive.GetEntry("foo.txt");
    // do something with the inner file
}
Run Code Online (Sandbox Code Playgroud)