none
replace 1 value in a json file RRS feed

  • Question

  • Hi,

    I'm trying to use a nested json file. I create the file with this:

    I am using Newtonsoft.Json

    [Serializable]
    public class FormParams
    {
        //system.drawing.rectangle = 10; 10; 700; 500 ==> x, y, width, height
        public int FrmX { get; set; }
        public int FrmY { get; set; }
        public int FrmHeight { get; set; }
        public int FrmWidth { get; set; }
        public int FrmWindowState { get; set; }
    
        [NonSerialized]
        public string SettingsFilePath;
    }
    
    public class FormSettings
    {
        public List<FormParams> FormMain { get; set; }
    }
    
    
    private void button1_Click(object sender, EventArgs e)
    {
        var FormPos = new FormSettings()
        {
            FormMain = new List<FormParams>()
            {
                new FormParams()
                {
                    FrmX = this.Location.X,
                    FrmY = this.Location.Y,
                    FrmHeight = this.Height,
                    FrmWidth = this.Width,
                    FrmWindowState = 0
                }
            }
        };
        string json = JsonConvert.SerializeObject(FormPos, Formatting.Indented);
        File.AppendAllText(@"c:\TEST.txt", json);  //add file.exists
    }

    The resulting json text file is:

    {
      "FormMain": [
        {
          "FrmX": 50,
          "FrmY": 50,
          "FrmHeight": 488,
          "FrmWidth": 816,
          "FrmWindowState": 0
        }
      ]
    }

    How can replace the value of "FrmHeight" without deleting the whole file and write it again.

    Greatings,

    Hans

    Thursday, April 2, 2020 7:08 PM

Answers

  • Hi HansvB69,

    Thank you for posting here.

    If you want to use C # to modify the values in a file, the first step is to read the contents of this file, then modify it, and finally write it to the file.

    Several methods I know are based on these steps, and to be precise, this did not delete the file, only rewrite its contents.

    This may be necessary.

    One way to modify it.

                string json = File.ReadAllText(@"d:\test\txt\Test.txt");
                dynamic jsonObj = JsonConvert.DeserializeObject(json);
                jsonObj["FormMain"][0]["FrmHeight"] = "500";
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(@"d:\test\txt\Test.txt", output);

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by HansvB69 Friday, April 3, 2020 1:27 PM
    Friday, April 3, 2020 2:25 AM

All replies

  • Using conventional file operations appending will not create a well formed json structure (see Microsoft source code below) which means you need to recreate the file.

    public static void AppendAllText(string path, string contents, Encoding encoding)
    {
      if (path == null)
        throw new ArgumentNullException(nameof (path));
      if (encoding == null)
        throw new ArgumentNullException(nameof (encoding));
      if (path.Length == 0)
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
      File.InternalAppendAllText(path, contents, encoding);
    }
    
    private static void InternalAppendAllText(string path, string contents, Encoding encoding)
    {
      using (StreamWriter streamWriter = new StreamWriter(path, true, encoding))
        streamWriter.Write(contents);
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, April 2, 2020 7:28 PM
    Moderator
  • Hi HansvB69,

    Thank you for posting here.

    If you want to use C # to modify the values in a file, the first step is to read the contents of this file, then modify it, and finally write it to the file.

    Several methods I know are based on these steps, and to be precise, this did not delete the file, only rewrite its contents.

    This may be necessary.

    One way to modify it.

                string json = File.ReadAllText(@"d:\test\txt\Test.txt");
                dynamic jsonObj = JsonConvert.DeserializeObject(json);
                jsonObj["FormMain"][0]["FrmHeight"] = "500";
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(@"d:\test\txt\Test.txt", output);

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by HansvB69 Friday, April 3, 2020 1:27 PM
    Friday, April 3, 2020 2:25 AM