Home > other >  c# File.WriteAllText overwriting new text on old Text
c# File.WriteAllText overwriting new text on old Text

Time:09-20

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

CodePudding user response:

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

  • Related