2016-10-24 28 views
0

如何在web api中將文件的一部分讀取爲流並對此流執行操作而不將整個文件存儲在內存中?注意:我不想在閱讀之前將文件保存到任何地方 - 它會上傳到web api控制器。Web API 2 - 流讀取文件

但我真正想爲實現以下僞代碼:

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; 
     } 
    } 
} 
+0

如果文件未保存,則表示是內存。否則,你不可能讀取文件 – Tinwor

+0

因此,發佈控制器時,從頭開始將整個文件存儲在內存中? – user2330270

+0

它不從客戶端流? – user2330270

回答

0

由於這裏找到: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。