Search code examples
c#fileiotext-indent

How to save file content without modifying the space or indents


I am using the below code to read and update the text file.

    using (StreamReader r = new StreamReader(filepath))
    {
      var json = r.ReadToEnd();
      AppSettings rootObject = JsonConvert.DeserializeObject<Settings>(json);
      rootObject.Settings.Size = 20;
      output = JsonConvert.SerializeObject(rootObject);
    }

    //Save back to the same file
    File.WriteAllText(filepath, output);

Before reading file content was looking like this

   {
       "Settings": {
           "Size": 220, 
   }

Post update, file content shows in a single line as follow

  {"Settings":{"Size":20}}

How can I retain the file contains spaces or indents.


Solution

  • You can instruct Json.NET to indent the output by supplying "Indented" for Formatting:

    output = JsonConvert.SerializeObject(rootObject , Formatting.Indented);
    

    While this won't necessarily format the file exactly as the original, it will be output in an indented fashion.

    Try it online

    If you need to further control how text is indented, you can create an instance of JsonSerializer and pass a JsonTextWriter to its Serialize method. The JsonTextWriter has Indentation (how many characters to indent by) and IndentChar (which character to use, e.g. ' ' for space, or '\t' for tab) which allow you to control the result.