1

您如何在 web api 中将文件的一部分作为流读取并对该流执行操作而不将整个文件放入内存中?注意:我不想在阅读之前将文件保存在任何地方 - 它已上传到 Web api 控制器。

但我真正想要的是实现以下伪代码:

foreach file in Request
{
    using (var sr = new StreamReader(fileStream))
    {
         string firstLine = sr.ReadLine() ?? "";
         if (firstLine contains the magic I need)
         {
             // would do something with this line, 
             // then scrap the stream and start reading the next file stream
             continue; 
         }
    }
}
4

1 回答 1

1

如此处所示:http : //www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/

您可以“强制 Web API 进入处理上传文件的流模式,而不是在内存中缓冲整个请求输入流”。

public class NoBufferPolicySelector : WebHostBufferPolicySelector
{
   public override bool UseBufferedInputStream(object hostContext)
   {
      var context = hostContext as HttpContextBase;

      if (context != null)
      {
         if (string.Equals(context.Request.RequestContext.RouteData.Values["controller"].ToString(), "uploading", StringComparison.InvariantCultureIgnoreCase))
            return false;
      }

      return true;
   }

   public override bool UseBufferedOutputStream(HttpResponseMessage response)
   {
      return base.UseBufferedOutputStream(response);
   }
}

public interface IHostBufferPolicySelector
{
   bool UseBufferedInputStream(object hostContext);
   bool UseBufferedOutputStream(HttpResponseMessage response);
}

不幸的是,您似乎无法使用帖子中提到的 Web API 来解决它,因为这严重依赖于 system.web。

于 2016-10-24T14:49:12.010 回答