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.
You can instruct Json.NET to indent the output by supplying "Indented" for
Formatting: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
JsonSerializerand pass aJsonTextWriterto itsSerializemethod. TheJsonTextWriterhasIndentation(how many characters to indent by) andIndentChar(which character to use, e.g.' 'for space, or'\t'for tab) which allow you to control the result.