iCalendar 是一套RFC 制式用作排程管理 (RFC 5545), iCal.net 是一套 C# 套件以存取ics 檔案. 在此示範中, 利用政府的公眾假期做示範, 如何存取ics 檔案並deserialize 作object.CalendarReader.cs
public class CalendarReader { public IList<CalendarEvent> LoadCalendarEventsByFile(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException("File " + filePath + " could not be found."); string icalText = File.ReadAllText(filePath); IList<CalendarEvent> calendarEvents = Calendar.Load<CalendarEvent>(icalText); return calendarEvents; } public IList<CalendarEvent> LoadCalendarEventsByHttp(string url, string httpMethod = "GET") { HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.Method = httpMethod; IList<CalendarEvent> calendarEvents = new List<CalendarEvent>(); try { using (WebResponse webResponse = httpRequest.GetResponse()) { using (Stream webResponseStream = webResponse.GetResponseStream()) { StreamReader streamReader = new StreamReader(webResponseStream); string responseText = streamReader.ReadToEnd(); Calendar calendar = Calendar.Load(responseText); calendarEvents = calendar.Events.ToList(); } } } catch (Exception ex) { throw(ex); } return calendarEvents; } }
MainWindowViewModel.cs
public class MainWindowViewModel { public ObservableCollection<CalendarEvent> CalendarEvents; private CalendarReader _calendarReader = new CalendarReader(); public MainWindowViewModel() { CalendarEvents = new ObservableCollection<CalendarEvent>(_calendarReader.LoadCalendarEventsByHttp("http://www.1823.gov.hk/common/ical/en.ics")); } }
利用HTTPWebRequest 讀取檔案, 並將Response stream 作string, 並用iCal.net.load() 讀取.
參考資料
- iCal.net, Github
https://github.com/rianjs/ical.net - ICalendar, Wikipedia
https://en.wikipedia.org/wiki/ICalendar
Leave a Reply