如何写入JSON文件中的新行? C#

时间:2018-02-04 00:07:40

标签: c# json serialization json.net discord

所以我现在用purge命令创建一个Discord bot。但是,我想写一个文件将时间,作者和消息量作为日志删除。

我正在使用Newtonsoft.Json,我的代码就是看台。

using (StreamWriter file = File.CreateText(@"C:\Users\COCON\source\repos\DiscordAdmin\DiscordAdmin\Logs\Purge.json")) //create json file at this path.
        {
            JsonSerializer serializer = new JsonSerializer();
            //serialize object directly into file stream
            serializer.Serialize(file, LocalTime + ": " + Sender + " has executed the purge command on " + message + " messages"); //Serialize the time, the author of the command and how many messages they purged
        }

此代码的问题是每次尝试记录给定命令时它只是在第一个日志上写入。那么我该如何强制它每次写入一个新行呢?我宁愿继续使用这种方法。

2 个答案:

答案 0 :(得分:1)

修改 我之前的回答(如下)解决了所述的问题。但正如评论中指出的那样,它不会产生有效的json文件。只是在文件的每一行中有效的json。以下将生成一个包含多个条目的有效json文件:

List<object> log = new List<object>();
            JsonSerializer serializer = new JsonSerializer();
        string path = @"C:\Users\COCON\source\repos\DiscordAdmin\DiscordAdmin\Logs\Purge.json";

        if (System.IO.File.Exists(path))
        {
            using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
            {
                Newtonsoft.Json.JsonReader jreader = new Newtonsoft.Json.JsonTextReader(reader);
                log = serializer.Deserialize<List<object>>(jreader);
            }
        }

        using (System.IO.StreamWriter file =
        new System.IO.StreamWriter(path, false))
        {
            object logEntry = LocalTime + ": " + Sender + " has executed the purge command on " + message + " messages";
            log.Add(logEntry);

            serializer.Serialize(file, log); //Serialize the time, the author of the command and how many messages they purged
        }

上一个答案:(在每一行中生成有效的json,但无效的json文件)

using (System.IO.StreamWriter file =
        new System.IO.StreamWriter(@"C:\Users\COCON\source\repos\DiscordAdmin\DiscordAdmin\Logs\Purge.json", true))
        {
            JsonSerializer serializer = new JsonSerializer();
            //serialize object directly into file stream
            serializer.Serialize(file, LocalTime + ": " + Sender + " has executed the purge command on " + message + " messages"); //Serialize the time, the author of the command and how many messages they purged
        }

true ”值表示附加,而不是创建新文件或覆盖。似乎 CreateText 没有附带该选项。 来自 File.CreateText 文档:

  

此方法相当于StreamWriter(String,Boolean)   构造函数重载,append参数设置为false。

File.CreateText

StreamWriter (String, Boolean)

答案 1 :(得分:0)

你每次都在创作。您可以附加到文件名以每次创建不同的文件或使用System.IO.File.WriteAllText(filePath,jsonData);只写入已经存在的文件