File is empty and I don't understand why. Asp.

2019-07-19 14:46发布

问题:

I am trying to use the built in asp.net file result to return a file that I am trying to make through a file stream. I am using Dday.ical to make my calendar for export

    MemoryStream export = new MemoryStream();         
    iCalendarSerializer serializer = new iCalendarSerializer(iCal);
    serializer.Serialize(export,System.Text.Encoding.Default);
    return export;

Here is my actionResult

public ActionResult ExportCalendar()
{
    string userName = User.Identity.Name;
    Guid userId = membershipS.GetUsersId(userName);
    var calendarStream = calendarS.ExportCalendar(userId);
    return File(calendarStream, "text/calendar", "test.ics");       
}

When I download the file it is 0bytes.

回答1:

Try resetting the stream's position:

calendarStream.Position = 0;

That way when the FileResult starts reading from the stream it will read it from the beginning instead of from the end (after which there are obviously no more bytes!).