using System; using System.IO; using System.Xml.Serialization; public sealed class SyncSettings { private static readonly string SettingsPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DailyFileSync", "settings.xml"); private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(SyncSettings)); public string Source { get; set; } public string Destination { get; set; } public int ScheduledMinute { get; set; } public DateTime LastScheduledDate { get; set; } public SyncSettings() { ScheduledMinute = 18 * 60; } internal bool IsConfigured { get { return !String.IsNullOrWhiteSpace(Source) && !String.IsNullOrWhiteSpace(Destination); } } internal bool IsDue(DateTime now) { return IsConfigured && LastScheduledDate.Date < now.Date && now.Hour * 60 + now.Minute >= ScheduledMinute; } internal static SyncSettings Load() { if (!File.Exists(SettingsPath)) return new SyncSettings(); using (FileStream input = File.OpenRead(SettingsPath)) { SyncSettings settings = (SyncSettings)Serializer.Deserialize(input); if (settings.ScheduledMinute < 0 || settings.ScheduledMinute >= 24 * 60) throw new IOException("保存的同步时间无效。"); return settings; } } internal void Save() { string directory = Path.GetDirectoryName(SettingsPath); Directory.CreateDirectory(directory); string temporary = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".tmp"); try { using (FileStream output = new FileStream(temporary, FileMode.CreateNew)) Serializer.Serialize(output, this); if (File.Exists(SettingsPath)) File.Replace(temporary, SettingsPath, null); else File.Move(temporary, SettingsPath); } finally { if (File.Exists(temporary)) File.Delete(temporary); } } }