简体   繁体   中英

Error while copying content to a stream.?

I am exporting excel file using WebApi but it throws an exception and I don't know why. I googled it and haven't found any solution.

Exeption:

    <Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>Error while copying content to a stream.</ExceptionMessage>
    <ExceptionType>System.Net.Http.HttpRequestException</ExceptionType>
    <StackTrace>
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at Microsoft.AspNet.WebApi.Extensions.Compression.Server.BaseServerCompressionHandler.<HandleCompression>d__17.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at Microsoft.AspNet.WebApi.Extensions.Compression.Server.BaseServerCompressionHandler.<SendAsync>d__15.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()
    </StackTrace>
    <InnerException>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>Cannot access a closed Stream.</ExceptionMessage>
    <ExceptionType>System.ObjectDisposedException</ExceptionType>
    <StackTrace>
    at System.IO.__Error.StreamIsClosed() at System.IO.MemoryStream.get_Position() at System.Net.Http.StreamToStreamCopy.StartAsync()
    </StackTrace>
    </InnerException>
    </Error>

My Code is :

[AllowAnonymous]
[HttpGet]
[Route("api/AddPatient/ExportToExcel")]
public HttpResponseMessage ExportToExcel()
{
    try
    {
        MemoryStream dataStream = Utility.GetFile();

        HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
        httpResponseMessage.Content = new StreamContent(dataStream);
        httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Test.xlsx";
        httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return httpResponseMessage;
    }
    catch (Exception ex)
    {
        throw;
    }
}  

GetFile function as below for getting excel memorystream Note: using NPOI i am createting excel file

public static MemoryStream GetFile()
        {
            MemoryStream stream =null;
            XSSFWorkbook wb = new XSSFWorkbook();
            ISheet sheet = wb.CreateSheet("Test");
            var row = sheet.CreateRow(0);
            var cell = row.CreateCell(0);
            cell.SetCellValue("Test");

            using ( stream = new MemoryStream())
            {
                wb.Write(stream);    
            } 

            return stream;
        }

You need to be careful when dealing with the stream object.

But I think your function to get dataStream also wrong. More code perhaps?

try
{
    using(MemoryStream dataStream = Utility.GetFile())
    {
      // read from beginning 
      dataStream.Position = 0;

      HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
      httpResponseMessage.Content = new StreamContent(dataStream);
      httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
      httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Test.xlsx";
      httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

      return httpResponseMessage;
    }
}
catch (Exception ex)
{
    throw;
}

Your GetFile cannot wrap using statement, that will close your memory stream object.

 // try this
 public static MemoryStream GetFile()
    {
        MemoryStream stream = new MemoryStream();
        // do your thing
        XSSFWorkbook wb = new XSSFWorkbook();
        ISheet sheet = wb.CreateSheet("Test");
        var row = sheet.CreateRow(0);
        var cell = row.CreateCell(0);
        cell.SetCellValue("Test");

        wb.Write(stream);    
        // reset position here
        stream.Position = 0;

        return stream;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM