簡體   English   中英

如何將 stream 的 Json 數據保存到 C# Windows Forms 應用程序中的文本文件?

[英]How can I save a stream of Json data to a text file in C# Windows Forms app?

我有一個 stream 的數據作為 Json 文件傳入,我試圖將它保存到一個文本文件中,我在下面讓它工作但是,當我檢查文件時,它只收到了最后一個 Json 消息已保存,我正在嘗試獲取它,以便在保存一行后進入新行並在下面打印最新的 Json 消息。 目前它將打印 1000 行,但它們都是相同的,並且與收到的最新 Json 相匹配。

任何幫助將非常感激。

void ReceiveData() //This function is used to listen for messages from the flight simulator
{
    while (true)
    {
        NetworkStream stream = client.GetStream(); //sets the network stream to the client's stream
        byte[] buffer = new byte[256]; //Defines the max amount of bytes that can be sent
        int bytesRead = stream.Read(buffer, 0, buffer.Length);

        if (bytesRead > 0)
        {
            string jsonreceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); //Converts the received data into ASCII for the json variable
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            TelemetryUpdate telemetry = serializer.Deserialize<TelemetryUpdate>(jsonreceived);
            this.Invoke(new Action(() => { TelemetryReceivedLabel.Text = jsonreceived; 
            })) ;

            Updatelabels(telemetry); //runs the update labels function with the telemetry data as an argument
                
            File.Delete(@"c:\temp\BLACKBOX.txt"); // this deletes the original file
            string path = @"c:\temp\BLACKBOX.txt"; //this stores the path of the file in a string                                  

            using (StreamWriter sw = File.CreateText(path)) // Create a file to write to.
            {
                for (int i = 0; i<10000; i++)
                {
                    sw.Write(jsonreceived.ToString()); //writes the json data to the file
                }
            }
        }
    }
}

根據 File.CreateText 的File.CreateText文檔:

創建或打開用於寫入 UTF-8 編碼文本的文件。 如果該文件已經存在,則其內容將被覆蓋。

因此,每次調用File.CreateText時,您都會創建一個新的 StreamWriter,它將覆蓋文件的內容。 嘗試使用File.AppendText來代替您離開的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM