c#如何相应地捕获数据
目前,我正在从串行端口接收数据字符串(RxString)。比如c#如何相应地捕获数据,c#,string,C#,String,目前,我正在从串行端口接收数据字符串(RxString)。比如 T 22 27.0 T 22 27.0 T 21 25.0 T 22 26.8 一行一行地 首先,我尝试拆分字符串以提取中间数字,以便进行比较 string[] number = RxString.Split(' '); string unit = split[1]; 然后,我通过 int count = 0; string x = ""; if (x == unit) { count++
T 22 27.0
T 22 27.0
T 21 25.0
T 22 26.8
一行一行地
首先,我尝试拆分字符串以提取中间数字,以便进行比较
string[] number = RxString.Split(' ');
string unit = split[1];
然后,我通过
int count = 0;
string x = "";
if (x == unit)
{
count++;
}
else
{
count = 1;
x = unit;
}
if (count == 4)
{
StreamWriter MyStreamWriter = new StreamWriter(@"C:\Users\acer\Documents\Data3.txt", true); //True tell SW to append to file instead of overwriting
MyStreamWriter.Write(time + " " + RxString + "\r\n"); //Write time + string
MyStreamWriter.Flush();
MyStreamWriter.Close();
count = 0; //reset count
}
我所期望的是:
T 22 24.0
T 22 24.0
T 22 24.0
T 22 24.0
T 23 26.7
T 20 25.0
那么我的.txt文件中应该显示的是
T 22 24.0
T 22 24.0
T 22 24.0
T 22 24.0
10:24:20 T 23 26.7
10:24 40 T 20 25.0
问题是:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff");
RxString = serialPort1.ReadLine();
string[] split = RxString.Split('.'); //split RxString at '.'
string dp = split[1]; //dp contains digit behind '.'
Char c = dp[0]; //c = first decimal place
split[1] = c.ToString();
RxString = split[0] + "." + split[1]; //Re-combine Rxstring
this.Invoke(new EventHandler(DisplayText));
string[] number = RxString.Split(' ');
string unit = split[1];
if (x == unit)
{
count++;
}
else
{
count = 1;
x = unit;
}
if (count == 4)
{
StreamWriter MyStreamWriter = new StreamWriter(@"C:\Users\acer\Documents\Data3.txt", true); //True tell SW to append to file instead of overwriting
MyStreamWriter.Write(time + " " + RxString + "\r\n"); //Write time + string
MyStreamWriter.Flush();
MyStreamWriter.Close();
count = 0; //reset count
}
您可以尝试进行数据记录。使用
文件。AppendAllText(…)
比在流中乱搞要干净得多。@Sachu不。。有什么建议吗?@Sachu一枪?Rxstring实际上代表1行tho..@Sachu oh。。我是通过串口接收的。。该端口将向sys提供data@Enigmativity你是说这个?AppendAllText(“C:\Users\acer\Documents\Data3.txt”,time+“”+RxString+“\r\n”);使用File.AppendAllText(…)
比在流中乱搞要干净得多。@Sachu没有。。有什么建议吗?@Sachu一枪?Rxstring实际上代表1行tho..@Sachu oh。。我是通过串口接收的。。该端口将向sys提供data@Enigmativity你是说这个?AppendAllText(“C:\Users\acer\Documents\Data3.txt”,time+“”+RxString+“\r\n”);