C# Web API 2-流读取文件

C# Web API 2-流读取文件,c#,asp.net-web-api2,webapi2,C#,Asp.net Web Api2,Webapi2,如何在web api中将文件的一部分作为流读取,并对该流执行操作,而不将整个文件存储在内存中?注意:我不想在读取之前将文件保存在任何地方-它已上载到web api控制器 但我真正想要的是实现以下伪代码: foreach file in Request { using (var sr = new StreamReader(fileStream)) { string firstLine = sr.ReadLine() ?? ""; if (firs

如何在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; 
         }
    }
}
如图所示:

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


不幸的是,您似乎无法使用本文中提到的Web API,因为它严重依赖system.Web

如果文件未保存,则表示该文件是内存。否则,在发布控制器时,您无法读取文件。控制器从一开始就将整个文件存储在内存中?它不会从客户端进行流式传输?很抱歉,我不明白。您的pseudcode与文件上载或文件读取相关,但如果您只需要第一部分,则不需要读取整个文件流
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);
}