public static bool TryLoad() { lock (Sync) { try { var fileExists = File.Exists(SettingsFilePath); var deserializer = new XmlSerializer(typeof(GlobalSettingsStorage)); using (var reader = File.Open(SettingsFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { GlobalSettingsStorage settings = null; if (!fileExists) { settings = new GlobalSettingsStorage(); deserializer.Serialize(reader, settings); } else { settings = (GlobalSettingsStorage)deserializer.Deserialize(reader); } _currentLanguage = new CultureInfo(settings.CurrentLanguageShortName); _pointsCount = settings.PointsCount; } _isLoaded = true; } catch (InvalidOperationException ex) when(ex.InnerException is XmlException) { LoadedSuccessfully = false; LoadedWithException = new SettingsLoadingException("XML settings file corrupted", ex); return(false); } catch (UnauthorizedAccessException ex) { LoadedSuccessfully = false; LoadedWithException = new SettingsLoadingException("You do not have access to the settings file.", ex); return(false); } catch (Exception ex) when(ex is PathTooLongException || ex is DirectoryNotFoundException || ex is IOException) { LoadedSuccessfully = false; LoadedWithException = new SettingsLoadingException("Failed to load settings file", ex); return(false); } return(true); } }
public static void Save() { lock (Sync) { if (!_isLoaded) { throw new InvalidOperationException("Load settings first"); } var serializer = new XmlSerializer(typeof(GlobalSettingsStorage)); using (var file = File.Create(SettingsFilePath)) { var settings = new GlobalSettingsStorage { CurrentLanguageShortName = CurrentLanguage.Name, PointsCount = PointsCount }; serializer.Serialize(file, settings); } } }