问题描述
下面code工作,但我想知道,如果的MemoryStream
创建正确关闭。应如何进行还是 FileStreamResult
处理一下吗?
公共FileStreamResult DownloadBudgetedRoleOpportunities(
GUID projectGuid,
IEnumerable的<的Guid> guidRequiredRoles)
{
VAR rolebroker =新ProjectRoleBudgetBroker();
VAR memstream = rolebroker.CreateBudgetedRoleOpportunies(
projectGuid,
guidRequiredRoles);
VAR FSR =新FileStreamResult(memstream,应用程序/ CSV)
{
FileDownloadName =RoleOpportunities.csv
};
// memstream.Close();抛出异常
返回FSR;
}
在 FileStreamResult
会为你做的。如有疑问随时检查code,因为code从不撒谎,因为ASP.NET MVC是开源它更容易查看code。
在谷歌快速搜索FileStreamResult.cs,您可以验证在 WriteFile的
方法的流是使用正确设置在使用
语句。 (没有双关语意)
保护覆盖无效WriteFile的(Htt的presponseBase响应){
//数据抓取块,并写入到输出流
流的OutputStream = response.OutputStream;
使用(的FileStream){
byte []的缓冲区=新的字节[_bufferSize]
而(真){
INT读取动作= FileStream.Read(缓冲液,0,_bufferSize);
如果(读取动作== 0){
//没有更多的数据
打破;
}
outputStream.Write(缓冲液,0,读取动作);
}
}
}
The following code works, but I'm wondering if the MemoryStream
created is closed properly. How should this be performed or does FileStreamResult
handle it for me?
public FileStreamResult DownloadBudgetedRoleOpportunities(
Guid projectGuid,
IEnumerable<Guid> guidRequiredRoles)
{
var rolebroker = new ProjectRoleBudgetBroker();
var memstream = rolebroker.CreateBudgetedRoleOpportunies(
projectGuid,
guidRequiredRoles);
var fsr = new FileStreamResult ( memstream, "application/csv" )
{
FileDownloadName = "RoleOpportunities.csv"
};
// memstream.Close(); throws exception
return fsr;
}
The FileStreamResult
will do that for you. When in doubt always check the code, because the code never lies and since ASP.NET MVC is open source it's even more easy to view the code.
A quick search on Google for FileStreamResult.cs lets you verify that in the WriteFile
method the stream is correctly disposed using the using
statement. (no pun intended)
protected override void WriteFile(HttpResponseBase response) {
// grab chunks of data and write to the output stream
Stream outputStream = response.OutputStream;
using (FileStream) {
byte[] buffer = new byte[_bufferSize];
while (true) {
int bytesRead = FileStream.Read(buffer, 0, _bufferSize);
if (bytesRead == 0) {
// no more data
break;
}
outputStream.Write(buffer, 0, bytesRead);
}
}
}
这篇关于随着FileStreamResult,如何将MemoryStream关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!