2009-05-26 14 views
19

Sto generando file ics (iCalendar o RFC 2445 o comunque li chiami) utilizzando una libreria che serializza i contenuti ical in un MemoryStream, o in realtà qualsiasi tipo di stream.FileResult con MemoryStream fornisce risultati vuoti .. qual è il problema?

Ecco il mio pezzo di codice:

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

Il mio problema è che FS contiene alcuni contenuti, ma il controllore restituisce file vuoto - con una corretta mimetype e il nome. Probabilmente mi manca qualcosa con la gestione del flusso ma non riesco a capire cosa.

Qualcuno può aiutarmi qui? Grazie in anticipo.

risposta

41

Solo un'ipotesi: è necessario Seek tornare all'inizio dello streaming prima di restituirlo?

fs.Seek(0, 0); 
+2

Bingo! Grazie mille. –

+1

Grazie Matt! Questo mi ha fatto risparmiare un sacco di tempo. Così semplice ma facilmente trascurato. – jhappoldt

0
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; 
Problemi correlati