从动作返回文件时,流是否会被处置?

时间:2017-02-15 00:39:03

标签: c# asp.net-core asp.net-core-mvc streamwriter memorystream

我正在将字符串写入export class UserInfoComponent extends Component { constructor(props){ super(props); this.state = {user: this.props.user} } componentWillReceiveProps(nextProps){ this.setState({user: nextProps.user}) } render() { if(this.state.user) return ( <h1>{this.state.user.firstName}</h1> ); return ( <h1>loading</h1> ) } } 我需要将流返回到Controller Action,以便将其作为文件发送下载。

通常,我将Stream包装在using语句中,但是,在这种情况下,我需要返回它。我退货后还能处理吗?或者我需要以某种方式自行处理它?

MemoryStream

Controller Action返回文件:

//inside CsvOutputFormatter
public Stream GetStream(object genericObject)
{
    var stream = new MemoryStream();
    var writer = new StreamWriter(stream, Encoding.UTF8);
    writer.Write(_stringWriter.ToString());
    writer.Flush();
    stream.Position = 0;
    return stream;
}

1 个答案:

答案 0 :(得分:10)

根据此处的源代码 aspnetwebstack/src/System.Web.Mvc/FileStreamResult.cs

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);
        }
    }
}

调用

时传递的流是FileStream
return File(stream, "application/octet-stream", "forums.csv");

<强>更新

您的问题最初被标记为Asp.Net MVC,但代码看起来像是最新的核心框架。

在那里找到它虽然写得不一样,但它在技术上做同样的事情。

aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/Infrastructure/FileStreamResultExecutor.cs

private static async Task WriteFileAsync(ActionContext context, FileStreamResult result)
{
    var response = context.HttpContext.Response;
    var outputStream = response.Body;

    using (result.FileStream)
    {
        await result.FileStream.CopyToAsync(outputStream, BufferSize);
    }
}