.net – 使用FileStreamResult,MemoryStream是如何关闭的?

前端之家收集整理的这篇文章主要介绍了.net – 使用FileStreamResult,MemoryStream是如何关闭的?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码工作,但我想知道是否正确关闭创建的MemoryStream。应该如何执行或FileStreamResult为我处理它?
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;
}

解决方法

FileStreamResult会为你做。当有疑问总是检查代码,因为代码永远不会说谎,并且由于ASP.NET MVC是开源的,它更容易查看代码

通过Google for FileStreamResult.cs快速搜索,您可以验证在WriteFile方法中,使用using语句正确处理流。 (无双关意)

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,_bufferSize);
            if (bytesRead == 0) {
                // no more data
                break;
            }

            outputStream.Write(buffer,bytesRead);
        }
    }
}
原文链接:https://www.f2er.com/aspnet/254346.html

猜你在找的asp.Net相关文章