-1

Using Newston.Json to Store Balances to Bank Account. When I add new entry, it replaces the old one, I want to append key value pairs to existing notepad file, instead it replaces the old balances.

Key = Bank Name with Account

Value = Balance

Global Variable

List<KeyValuePair<string, float>> vals3 = new List<KeyValuePair<string, float>>();

// Now Add Balance to Accounts

BankWithAccount = BankList.Text + AccountNotextBox1.Text;
balance = float.Parse(BalanceTxtBox.Text);

vals3.Add(new KeyValuePair<string, float>(BankWithAccount, balance));
        using (StreamWriter sw = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Balances.txt")))
        {
            string json = JsonConvert.SerializeObject(vals3);
            sw.Write(json);
        }
Fawad
  • 153
  • 1
  • 4
  • 16
  • Are you appending key values or json? – auburg Aug 06 '21 at 21:30
  • A [well-formed JSON file](https://www.json.org/) has a single root value (object, array or primitive), so you cannot **append** a key/value pair to it. You must parse it and insert it. If you need to write frequently and read occasionally (e.g. as in writing a log file), as an alternative to JSON you might consider newline-delimited JSON, see [Serialize as NDJSON using Json.NET](https://stackoverflow.com/q/44787652/3744182) and [Line delimited json serializing and de-serializing](https://stackoverflow.com/q/29729063/3744182). – dbc Aug 06 '21 at 22:39

1 Answers1

0

From the docs for File.CreateText(String):

Creates or opens a file for writing UTF-8 encoded text. If the file already exists, its contents are overwritten. https://learn.microsoft.com/en-us/dotnet/api/system.io.file.createtext?view=net-5.0

What you probably want is File.AppendText(String):

Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendtext?view=net-5.0

bschellekens
  • 191
  • 6
  • When I write File.AppendText, I am getting following error: Newtonsoft.Json.JsonReaderException: 'Additional text encountered after finished reading JSON content: [. Path '', line 1, position 53.' – Fawad Aug 09 '21 at 16:12
  • I have found is this issue, when a same window is open, everything works fine but when i close window and reopen, then it replaces the text file, otherwise File.CreateText is appending text. – Fawad Aug 09 '21 at 18:54
  • So... are you creating 1 big JSON object or is each line an individual JSON object? – bschellekens Aug 17 '21 at 19:36