Подтвердить что ты не робот

FileResult с MemoryStream дает пустой результат.. какая проблема?

Я генерирую файлы ics (iCalendar или RFC 2445 или, тем не менее, вы их называете), используя библиотеку, которая сериализует содержимое iical в MemoryStream или фактически любой тип потока.

Вот мой кусок кода:

    public ActionResult iCal(int id) {

        MyApp.Event kiEvt = evR.Get(id);

        // Create a new iCalendar
        iCalendar iCal = new iCalendar();

        // Create the event, and add it to the iCalendar
        DDay.iCal.Components.Event evt = iCal.Create<DDay.iCal.Components.Event>();

        // Set information about the event
        evt.Start = kiEvt.event_date;
        evt.End = evt.Start.AddHours(kiEvt.event_duration); // This also sets the duration            
        evt.Description = kiEvt.description;
        evt.Location = kiEvt.place;
        evt.Summary = kiEvt.title;

        // Serialize (save) the iCalendar
        iCalendarSerializer serializer = new iCalendarSerializer(iCal);


        System.IO.MemoryStream fs = new System.IO.MemoryStream();

        serializer.Serialize(fs, System.Text.Encoding.UTF8);

        return File(fs, "text/calendar", "MyApp.wyd."+kiEvt.id+".ics");
    }

Моя проблема в том, что fs содержит некоторый контент, но контроллер возвращает пустой файл - с правильным типом и именем файла. Я, скорее всего, что-то пропустил с обработкой потока, но не могу понять, что.

Может кто-нибудь помочь мне здесь? Спасибо заранее.

4b9b3361

Ответ 1

Просто догадайтесь: вам нужно Seek вернуться к началу потока, прежде чем вы его вернете?

fs.Seek(0, 0);

Ответ 2

iCalendar iCal = new iCalendar();
foreach (CalendarItem item in _db.CalendarItems.Where(r => r.Start > DateTime.Now && r.Active == true && r.CalendarID == ID).ToList())
{
    Event evt = new Event();
    evt.Start = new iCalDateTime(item.Start);
    evt.End = new iCalDateTime(item.End);
    evt.Summary = "Some title";
    evt.IsAllDay = false;
    evt.Duration = (item.End - item.Start).Duration();
    iCal.Events.Add(evt);
}
// Create a serialization context and serializer factory. 
// These will be used to build the serializer for our object. 
ISerializationContext ctx = new SerializationContext();
ISerializerFactory factory = new DDay.iCal.Serialization.iCalendar.SerializerFactory();
// Get a serializer for our object
IStringSerializer serializer = factory.Build(iCal.GetType(), ctx) as IStringSerializer;
if (serializer == null) return Content("");
string output = serializer.SerializeToString(iCal);
var contentType = "text/calendar";
var bytes = Encoding.UTF8.GetBytes(output);
var result = new FileContentResult(bytes, contentType);
result.FileDownloadName = "FileName.ics";
return result;