Saturday, August 10, 2013

Creating iCalendar files in C#

iCalendar format is a new version of vCalendar format. iCalendar stores the event in simple text format. You can create an outlook appointment in outlook and save that item as .ics file and see its underlying format by opening it as notepad file and compile a string on your C# code with similar format and send that to browser as attachment file using Response.Write.

 
                StringBuilder sw = new StringBuilder();       
                sw.AppendLine("BEGIN:VCALENDAR");
                sw.AppendLine("VERSION:2.0");
                sw.AppendLine("METHOD:PUBLISH");
                
                //UnComment the Below Line to Add TimeZone
                /*sw.AppendLine("BEGIN:VTIMEZONE");
                sw.AppendLine("TZID:Arab Standard Time");
                sw.AppendLine("BEGIN:STANDARD");
                sw.AppendLine("DTSTART:16010101T000000");
                sw.AppendLine("TZOFFSETFROM:+0300");
                sw.AppendLine("TZOFFSETTO:+0300");
                sw.AppendLine("END:STANDARD");
                sw.AppendLine("END:VTIMEZONE");  */             

                sw.AppendLine("BEGIN:VEVENT");
                sw.AppendLine("CLASS:PUBLIC");
                sw.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmss}", DateTime.UtcNow));
                sw.AppendLine("DESCRIPTION: " + lblBody.Text);
                sw.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmss}", eventendDT));
                sw.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmss}", eventstartDT));
                sw.AppendLine("SEQUENCE:0");
                sw.AppendLine("UID:" + Guid.NewGuid().ToString());
                sw.AppendLine("LOCATION:" + lblLocation.Text);
                sw.AppendLine("SUMMARY;LANGUAGE=en-us:" + lblEventPlan.Text);                
                sw.AppendLine("END:VEVENT");
                sw.AppendLine("END:VCALENDAR");

                string FileName = "Event.ics";
                
                Response.Clear();
                Response.ContentType = "text/calendar";
                Response.AddHeader("content-disposition", "inline; filename=" + FileName);
                Response.Write(sw.ToString());
                Response.Flush();
                
Related Posts Plugin for WordPress, Blogger...