寻求C# CopyToAsync源码链接及ASP.NET Core 6流释放问题解答
关于ASP.NET Core 6.0中Stream的CopyToAsync与释放问题
一、需求:获取指定CopyToAsync方法的源码
需要获取C#中以下签名的CopyToAsync方法源码:
public System.Threading.Tasks.Task CopyToAsync (System.IO.Stream destination, System.Threading.CancellationToken cancellationToken);
二、问题场景与代码
在ASP.NET Core 6.0中实现Excel文件下载功能时遇到问题,相关代码如下:
namespace Magicodes.ExporterAndImporter.Excel.AspNetCore { /// <summary> /// 基类 /// </summary> public class XlsxFileResultBase : ActionResult { /// <summary> /// 下载Excel文件 /// </summary> /// <param name="context"></param> /// <param name="stream"></param> /// <param name="downloadFileName"></param> /// <returns></returns> protected virtual async Task DownloadExcelFileAsync(ActionContext context, Stream stream, string downloadFileName) { var response = context.HttpContext.Response; response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; if (downloadFileName == null) { downloadFileName = Guid.NewGuid().ToString("N") + ".xlsx"; } if (string.IsNullOrEmpty(Path.GetExtension(downloadFileName))) { downloadFileName += ".xlsx"; } context.HttpContext.Response.Headers.Add("Content-Disposition", new[] { "attachment; filename=" + HttpUtility.UrlEncode(downloadFileName) }); await stream.CopyToAsync(context.HttpContext.Response.Body); } } }
此前使用using声明MemoryStream时,触发了如下错误:
错误消息: Cannot access a closed Stream.
堆栈信息: at System.IO.MemoryStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
三、疑问
不清楚传入上述方法的Stream是否需要手动释放,想确认在ASP.NET Core 6.0返回文件流的场景下,该Stream是否会被自动释放,希望以源码作为依据。
内容的提问来源于stack exchange,提问作者Sheldon_XiTong
相关产品推荐
相关产品推荐

