How to generate an iCalendar file (ASP.NET/C#)

It is fairly simple to generate an iCalendar file (for calendar clients like Microsoft Outlook or Mozilla Sunbird) as it is just a plain text file with the extension 'ics'. A WebHandler is the best method of doing this.

Update (10 Feb 2006): Now works in Sunbird. When prompted to open / save the file, choose to download. Then in Sunbird, go to File > Import and browse for the saved file.

iCalendar.ashx

<%@ WebHandler Language="C#" Class="MyNamespace.iCalendar" %>
using System;
using System.Web;
namespace MyNamespace
{
 public class iCalendar: IHttpHandler 
 {
  
  public bool IsReusable
  {
   get
   {
    return true;
   }
  }

  string DateFormat
  {
    get
    {
      return "yyyyMMddTHHmmssZ"; // 20060215T092000Z
    }
  }
  
  
  public void ProcessRequest(HttpContext ctx)
  {
   DateTime startDate = DateTime.Now.AddDays(5);
   DateTime endDate = startDate.AddMinutes(35);
   string organizer = "foo@bar.com";
   string location = "My House";
   string summary = "My Event";
   string description = "Please come to\\nMy House";
   
   ctx.Response.ContentType="text/calendar";
   ctx.Response.AddHeader("Content-disposition", "attachment; filename=appointment.ics");
   
   ctx.Response.Write("BEGIN:VCALENDAR");
   ctx.Response.Write("\nVERSION:2.0");
   ctx.Response.Write("\nMETHOD:PUBLISH");
   ctx.Response.Write("\nBEGIN:VEVENT");
   ctx.Response.Write("\nORGANIZER:MAILTO:" + organizer);
   ctx.Response.Write("\nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat));
   ctx.Response.Write("\nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat));
   ctx.Response.Write("\nLOCATION:" + location);
   ctx.Response.Write("\nUID:" + DateTime.Now.ToUniversalTime().ToString(DateFormat) + "@mysite.com");
   ctx.Response.Write("\nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat));
   ctx.Response.Write("\nSUMMARY:" + summary);
   ctx.Response.Write("\nDESCRIPTION:" + description);
   ctx.Response.Write("\nPRIORITY:5");
   ctx.Response.Write("\nCLASS:PUBLIC");
   ctx.Response.Write("\nEND:VEVENT");
   ctx.Response.Write("\nEND:VCALENDAR");
   ctx.Response.End();
  }
 }
}

Comments

Mr. T said…
simple, straightforward, keepin it simple, stupid... props.
Eric Barr said…
I don't doubt that a Web Handler is the best way to do this, since I read that it saves overhead from the typical page class. But if you're not worried about the performance (I'm not) then I found that you can just put this code in the Page_Load of a typical .aspx page and remove the "ctx." on each line and it works that way too! Thanks for the post, it helped a lot!

Popular posts from this blog

Select box manipulation with jQuery

Basic Excel Spreadsheet Generation (ASP/ASP.NET)

Link: HTML Agility Pack (.NET)