Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# File.WriteAllText overwriting new text on old Text

While inserting new text into Json file its overwriting new text (insted of writing in new line).
Here is my code

public static void WriteToJson()
    {
        string filepath = @"../../SchemaList.json";
       // string filepath = @"C:\HoX_code\learning\Readjson\Readjson\SchemaList.json";

        List<SchemaInfo> _oscheme = new List<SchemaInfo>();
        _oscheme.Add(new SchemaInfo()
        {
            AuthenticateCmdlets= "AuthenticateCmdlets1",
            GetPowerState= "GetPowerState1",
            PowerOff= "PowerOff",
            PowerOn= "PowerOn",
        });
        string json = JsonConvert.SerializeObject(_oscheme.ToArray(), Formatting.Indented);
        using (StreamWriter sw = new StreamWriter(@"C:\HoX_code\learning\Readjson\Readjson\SchemaList.json"))
        {
             sw.Write(json);
        }
        ///  File.WriteAllText(@"../../SchemaList.json", json);
    }

Here i use File.WriteAllText & StreamWriter Both are working same

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is intended behaivour. Checking the documentation for File.WriteAllText it says

Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

(Emphasis mine)

You’re going to want to use File.AppendAllText, it’s documentation states

Appends the specified string to the file, creating the file if it does not already exist.

If you want to use streams, then the StreamWriter constructor has a parameter to specify whether or not to append or overwrite text in a file here (Credits go to @vernou, I totally forgot this constructor existed)

But do note that this will result in invalid JSON, as JSON may only have 1 base object and this will result in multiple. If you actually want to append to the serialized JSON object, the I recommend you check out How to Append a json file without disturbing the formatting

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading