我對流感到困惑,返回值和處置。即我使用Stream並想從方法返回流。下面的代碼:配置並返回值
public async Task<HttpResponseMessage> GetOverlayAsync(string fileUrl, string language, string strOCR)
{
HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
using (var stream = new FileStream(@"D:\\_forTest.jpg", FileMode.Open))
{
length = stream.Length;
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName("_forTest.jpg");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = length;
return result;
}
}
和
public async Task<HttpResponseMessage> GetOverlayAsync(string fileUrl, string language, string strOCR)
{
long length = 0;
HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
using (var stream = new FileStream(@"D:\\_forTest.jpg", FileMode.Open))
{
length = stream.Length;
result.Content = new StreamContent(stream);
}
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName("_forTest.jpg");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = length;
return result;
}
返回504狀態碼:
ReadResponse()失敗:服務器未返回爲此請求完全反應 。服務器返回0字節。
public async Task<HttpResponseMessage> GetOverlayAsync(string fileUrl, string language, string strOCR) { long length = 0; HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK); var stream = new FileStream(@"D:\\_forTest.jpg", FileMode.Open); length = stream.Length; result.Content = new StreamContent(stream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = Path.GetFileName("_forTest.jpg"); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentLength = length; return result; }
有時我得到的文件被阻止:
所以,按照我的理解,流當我們從法
出去如果我不調用Dispose在所有配置另一個過程。如何正確使用?
你的例子是否真的編譯?這些方法被標記爲「async」,但方法中沒有「await」。 – Sean
我在 –
之前刪除了不必要的代碼嘗試打開文件流如下:'new FileStream(@「D:\\ _ forTest.jpg」,FileMode.Open,FileAccess.Read,FileShare.Read);'當然不要配置它(發送給客戶後會自動爲您處理)。當你只做'新的FileStream(...,FileMode.Open)' - 它相當於'新的FileStream(...,FileMode.Open,FileAccess.ReadWrite,FileShare。讀)「,並且這將防止隨後打開相同的文件,即使是來自相同的進程。 – Evk