static JSettings _Load(string file, Type type, bool useDefault) { JSettings R = null; if (AFile.ExistsAsAny(file)) { try { if (useDefault) { AFile.Delete(file); } else { var b = AFile.LoadBytes(file); var opt = new JsonSerializerOptions { IgnoreNullValues = true, AllowTrailingCommas = true }; R = JsonSerializer.Deserialize(b, type, opt) as JSettings; } } catch (Exception ex) { string es = ex.ToStringWithoutStack(); if (useDefault) { AOutput.Write($"Failed to delete settings file '{file}'. {es}"); } else { string backup = file + ".backup"; try { AFile.Move(file, backup, IfExists.Delete); } catch { backup = "failed"; } AOutput.Write( $@"Failed to load settings from {file}. Will use default settings. {es} Backup: {backup}" ); } } } R ??= Activator.CreateInstance(type) as JSettings; R._file = file; R._loaded = true; //autosave if (Interlocked.Exchange(ref s_loadedOnce, 1) == 0) { AThread.Start(() => { for (; ;) { Thread.Sleep(2000); _SaveAllIfNeed(); } }, sta: false); AProcess.Exit += (unu, sed) => _SaveAllIfNeed(); //info: Core does not call finalizers when process exits } lock (s_list) s_list.Add(R); return(R); }