/// <summary> /// Save account data. /// </summary> /// <param name="saveReason">Reason why should save</param> /// <returns></returns> public bool SaveAccount(string saveReason = null) { Logger.Info(saveReason is null ? "Save data to file" : $"Save data to file: \"{saveReason}\""); var dirPath = Pri.LongPath.Path.GetDirectoryName(Constants.PathToPasswordsFile); if (!Pri.LongPath.Directory.Exists(dirPath)) { Pri.LongPath.Directory.CreateDirectory(dirPath); } try { string forFile = JsonConvert.SerializeObject(CurrentAccount); string forFileEncrypted = TripleDESHelper.EncryptString(forFile); var waitHandleName = Constants.PathToPasswordsFile.GetHashString <SHA256Managed>(); using (var waitHandleLocker = EventWaitHandleLocker.MakeWithEventHandle(true, EventResetMode.AutoReset, waitHandleName)) { using (var fileStream = Pri.LongPath.File.Open(Constants.PathToPasswordsFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { using (var streamWriter = new StreamWriter(fileStream)) { streamWriter.Write(forFileEncrypted); } } } return(true); } catch (Exception ex) { Logger.HandleException(ex); return(false); } }
/// <summary> /// Read file with account data. /// </summary> /// <returns><see cref="Account"/> instance.</returns> private void ReloadAccount() { if (Pri.LongPath.File.Exists(Constants.PathToPasswordsFile)) { try { var waitHandleName = Constants.PathToPasswordsFile.GetHashString <SHA256Managed>(); using (var waitHandleLocker = EventWaitHandleLocker.MakeWithEventHandle(true, EventResetMode.AutoReset, waitHandleName)) { using (var fileStream = Pri.LongPath.File.Open(Constants.PathToPasswordsFile, FileMode.Open)) { using (StreamReader streamReader = new StreamReader(fileStream)) { try { var fromFileEncrypted = streamReader.ReadToEnd(); var fromFileDecrypted = TripleDESHelper.DecryptString(fromFileEncrypted); CurrentAccount = JsonConvert.DeserializeObject <Account>(fromFileDecrypted); } catch (Exception ex) { Logger.HandleException(ex); if (CurrentAccount is null) { CurrentAccount = new Account(); } } } } } } catch (Exception ex) { Logger.Error(ex.ToString()); } } }