我有一个能够通过WebGet返回流的WCF服务。目前它能正常工作。 但是我想实现的是支持Range头,这样只返回文件的部分内容。 这是我的代码:
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设置为范围的起始值,但是如何从文件中某个位置获取一部分是最好的方法?
我是否需要创建MemoryStream并将相关字节写入其中? 这里流式传输的文件是视频文件,因此可能非常大。