我有一个作为Json文件传入的数据流,我试图将其保存到文本文件中,我已经在下面的这里工作,但是,当我检查文件时,它只保存了最后一个接收到的Json消息,我正在尝试让它保存一行后转到新的一行,并在下面打印最新的Json消息。目前它将打印let's说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
}
}
}
}
}
1条答案
按热度按时间vxqlmq5t1#
根据
File.CreateText
的.NET文档:建立或开启档案以写入UTF-8编码文字。如果档案已经存在,其内容会被覆写。
因此,每次调用
File.CreateText
时,您都在创建一个新的StreamWriter,它将覆盖文件的内容。请尝试使用File.AppendText
来继续上次的操作。