开发者

Serving a file from an action in Asp.Net MVC. Is it better to use byte[] or Stream?

W开发者_如何转开发hen we want to serve a file (non HTML) from an action we can use the File Action Result. The contructor can accept either a byte[] or a Stream. Which one is better? Why?

Thanks!


I would use a stream and I would try hard to stream data down to the client without ever load all data into a byte[] on the web server.

This is the only way you are sure you do not load files completely in the server memory, imagine 10 people downloading files of 100 Mb each, better to avoid the ASP.NET process to grow to 1GB RAM only because of that, with streaming you can do this :)


Neither is better or worse, use whichever one most suits your situation.

For eaxmple, if the file is on disk, it's probable that you will load it into a stream

var stream = File.OpeanRead("C:\myfile.ext")

There is no point turning this into a byte array.

However, if you have a file in memory, it might already be in a byte array. In this case there is no point turning it to a stream.


If your file is on disk, you can use FilePathResult : http://msdn.microsoft.com/en-us/library/system.web.mvc.filepathresult.aspx

This class uses HttpResponse.TransmitFile, which reads the file without buffering it to memory : http://msdn.microsoft.com/en-us/library/system.web.httpresponse.transmitfile.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜