Web API 2 - 流读取文件

时间:2016-10-24 12:05:32

标签: c# asp.net-web-api2 webapi2

如何在web api中只读取文件的一部分作为流并在此流上执行操作而不将整个文件存入内存?注意:我不想在阅读之前将文件保存到任何地方 - 它已上传到网络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; 
         }
    }
}

1 个答案:

答案 0 :(得分: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。