5
我有一個WCF服務,可以通過WebGet返回一個流。這工作很好。 但是我想實現的是對Range頭的支持,所以只返回文件的一部分。 這是我的代碼這一步:WCF服務 - 支持範圍:字節支持流文件?
public System.IO.Stream GetStream(string mElementID)
{
// build the filePath
FileInfo file = GetFile(mElementID);
try
{
FileStream videoStream = File.OpenRead(file.FullName);
if (request.Headers.AllKeys.Contains("Range"))
{
long startRange = ...; // get the start range from the header
long endRange = ...; // get the end range from the header
videoStream.Position = startRange;
// how can I set the end of the range?
//TODO: Don't forget to add the Content-Range header to the response!
}
WebOperationContext.Current.OutgoingResponse.ContentType = GetMimeType(file);
WebOperationContext.Current.OutgoingResponse.Headers.Add("Accept-Ranges", "bytes");
return videoStream;
}
catch (FileNotFoundException){}
catch (IOException ex)
{
throw ex;
}
// throw a 404
throw new WebFaultException(System.Net.HttpStatusCode.NotFound);
}
我只是創建一個FileStream,並返回。現在我想知道什麼是獲得該流的範圍的最佳方式。
我想我可以設置videoStream.Position該範圍的初始值,但什麼是文件到地方在文件中從 somwehere得到部分的最佳方式?
我是否必須創建一個MemoryStream並將相關字節寫入該字段? 這裏流式傳輸的文件是視頻文件,因此可能相當大。
謝謝你的回答,很好解釋。我擔心的是內存消耗,因爲視頻必須完全讀入內存。我正在使用的服務不會有很多用戶,所以這可能不會成爲問題,但我想知道是否有更好的方法,性能明智。 – Malyngo 2011-05-09 07:19:26
關於您的表現問題,可能值得發佈第二個問題。流對於性能來說是非常好的,但是在原始文章中顯示的實現中,我不相信你正在將整個流加載到內存中。根據我的建議只有緩衝區。希望有所幫助。 – Smudge202 2011-05-09 09:22:16