Monday, September 21, 2015

Export all events to iCal format programmatically


We all know about iCal format which is used to import the Calendar items to Outlook. We can able to export a single item to iCal using OOTB. But we doesn't have the option to get all the events in single .ics file. Here i am going to provide a code base to export all the events as .ics format

 StringBuilder sw = new StringBuilder();
                sw.AppendLine("BEGIN:VCALENDAR");
                sw.AppendLine("VERSION:2.0");
                sw.AppendLine("METHOD:PUBLISH");
                foreach (var item in items)
                {

                    sw.AppendLine("BEGIN:VEVENT");
                    sw.AppendLine("CLASS:PUBLIC");
                    sw.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmss}", DateTime.UtcNow));
                    sw.AppendLine("DESCRIPTION: " + Convert.Tostring(item["Description"]));
                    sw.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmss}", Convert.ToDateTime(item[EndDate]));
                    sw.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmss}", Convert.ToDateTime(item[StartDate]));
                    sw.AppendLine("SEQUENCE:0");
                    sw.AppendLine("UID:" + Guid.NewGuid().ToString());
                    sw.AppendLine("LOCATION:" + Convert.ToString(item["Location"]));
                    sw.AppendLine("SUMMARY;LANGUAGE=en-us:" + Convert.ToString(item["Title"]));
                    sw.AppendLine("END:VEVENT");
                }
                sw.AppendLine("END:VCALENDAR");

                Page.Response.Clear();
                Page.Response.ContentType = "text/calendar";
                Page.Response.AddHeader("content-disposition", "inline; filename=" + "Test.ics");
                Page.Response.Write(sw.ToString());
                Page.Response.Flush();

Put the above code base in your webpart. Then iCal format will work like an awesome.

1 comment: