[英]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.