Creating downloadable calendar item of SPListItem

Recently I prepared some code to download calendar item from SharePoint web part to user computer. I was lucky because the web part will only be used on details view of one list. The testing code I wrote was simple and short.


protected void downloadButton_Click(object sender, EventArgs e)
{
   
SPListItem item = SPContext
.Current.ListItem;

   
try
    {
       
string location = item["Location"] as string
;
       
string
subject = item.Title;
       
string description = item["Description"] as string
;

       
var beginDate = (DateTime)item["From"
];
       
var beginDateString = beginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"
);

       
var endDate = (DateTime)item["Thru"
];
       
var endDateString = endDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"
);

       
string
[] contents = {
               
"BEGIN:VCALENDAR"
,
               
"PRODID:-//My company//My product//EN"
,
               
"BEGIN:VEVENT"
,
               
"DTSTART:"
+ beginDateString,
               
"DTEND:"
+ endDateString,
               
"LOCATION:"
+ location,
               
"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:"
+ description,
               
"SUMMARY:" + subject, "PRIORITY:3"
,
               
"END:VEVENT"
,
               
"END:VCALENDAR"
};

       
HttpResponse response = HttpContext
.Current.Response;

        response.Clear();
        response.ContentType =
"text/calendar"
;
        response.AddHeader(
"Content-disposition", "attachment;filename=event.ics"
);
        response.Write(
string.Join("\r\n"
, contents));
        response.Flush();
        response.End();
    }
   
catch (System.Threading.ThreadAbortException
taex)
    {
       
// Ignore this exception
    }
}

Feel free to use this code if you like it.


One thought on “Creating downloadable calendar item of SPListItem

Leave a Reply

Your email address will not be published. Required fields are marked *