如何在ASP.NET 4.0中为iCal文件创建MemoryStream?

时间:2012-05-21 13:03:56

标签: asp.net c#-4.0 icalendar memorystream

我正在尝试使用memorystream(在ASP.NET 4.0中)创建一个ICS日历文件,如下所示:

using System.IO;
using System;

public MemoryStream GetMemoryStream()
{
    iCalendar iCal = new iCalendar();
    Event evt = iCal.Create<Event>();

    // Set information about the event
    evt.Start = new iCalDateTime(SomeStartTime);
    evt.End = new iCalDateTime(SomeEndTime);
    evt.Location = SomeLocation;
    evt.Description = SomeDescription;
    evt.Summary = SomeSummary;

    iCalendarSerializer serializer = new iCalendarSerializer(iCal);
    MemoryStream ms = new MemoryStream();
    serializer.Serialize(iCal, ms, Encoding.UTF8);
    return ms;
}

我想我错过了一些东西。任何人都可以帮我创建正确的MemoryStream对象吗?

注意:我需要MemorySteam个对象为System.Net.Mail.Attachment创建System.Net.Mail.MailMessage

1 个答案:

答案 0 :(得分:3)

据我所见,SerialStream正在处理MemoryStream。 我通过将日历转换为字符串然后将字符串转换为MemoryStream

来解决它
using System.IO;
using System;

public MemoryStream GetMemoryStream()
{
    iCalendar iCal = new iCalendar();
    Event evt = iCal.Create<Event>();

    // Set information about the event
    evt.Start = new iCalDateTime(SomeStartTime);
    evt.End = new iCalDateTime(SomeEndTime);
    evt.Location = SomeLocation;
    evt.Description = SomeDescription;
    evt.Summary = SomeSummary;

    iCalendarSerializer serializer = new iCalendarSerializer(iCal);
    MemoryStream ms = new MemoryStream();
    //serializer.Serialize(iCal, ms, Encoding.UTF8);
    var ics = serializer.SerializeToString(iCal);
    var bytes = System.Text.Encoding.UTF8.GetBytes(ics);
    ms.Write(bytes, 0, bytes.Length); 
    ms.Seek(0, SeekOrigin.Begin);
    return ms;
}