因此,我得到了一个作为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 newtwork 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 recieved 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 arguement
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条答案
按热度按时间5t7ly7z51#
根据
File.CreateText
的.NET文档:建立或开启档案以写入UTF-8编码文字。如果档案已经存在,其内容会被覆写。
因此,每次调用
File.CreateText
时,您都在创建一个新的StreamWriter,它将覆盖文件的内容。请尝试使用File.AppendText
来继续上次的操作。