(c#)串口通信,数据保存问题 在线等、、、、

串口接收命令并周期的采集数据,我想把采集的数据实时的存储成一个个的文件,文件名以每个周期的采集的时间去命名要怎么做啊 (也可以不这么做,只要能实现实时保存数据就成)。 private void serialPortDL_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{

try
{
DateTime dt = System.DateTime.Now; //实例化对象捕获系统当前时间
string t = dt.ToLongTimeString(); //将此实例的值转化为等效时间字符串值
t = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
Thread.Sleep(500);
//读入收到的数据。
int Len = serialPortDL.BytesToRead;
if (Len < 1)
{
return;
}
byte[] data = new byte[Len];
serialPortDL.Read(data, 0, Len);

//数据转十六进制字符串。
if (!checkBox1.Checked)
{
string Hex = PubFunction.BytesToHexString(data);
Hex = Hex.ToUpper();

textBox1.Invoke(new EventHandler(delegate
{
DoingHex = true; //***正在处理十六进制数据。

this.textBox1.Text += t + " 命令: 01 03 0008 0002 " + " 电量模块数据: " + Hex + "\r\n";
//textBox1.AppendText(Hex);
textBox1.ScrollToCaret(); //将控件的内容滚动到当前位置。
DoingHex = false;
}
));
}
while ( DoingHex)
Application.DoEvents(); //处理串口接收事件及其它系统消息。

}
catch (Exception Err)
{
MessageBox.Show(Err.Message, "");
}
}
private void timer1_DataCollection_Tick(object sender, EventArgs e)
{

if (serialPortDL.IsOpen)
{
{
string str = PubFunction.HexStrToStr("010300080002");//电量

string Crc = CRC16.CalHexStrCrc16(str);

try
{
string txt = "010300080002" + Crc;
//string txt = "01100004000306010600010001" + Crc;
byte[] EncodeByte = PubFunction.HexStringToBytes(txt);
int Len = EncodeByte.Length;
serialPortDL.Write(EncodeByte, 0, Len);

}
catch (Exception err)
{
MessageBox.Show(err.Message, "");
}

}
}
}

很简单
1.先System.IO的命名空间。
2.在定时器添加这几句.
StreamWriter writer = null;
string path = "c:\\";
writer = new StreamWriter(path+DateTime.Now.ToString("yyyyMMddhhssmm.txt"), true, Encoding.GetEncoding("gb2312"));
writer.Write(msg);
writer.Flush();追问

writer = new StreamWriter(path+DateTime.Now.ToString("yyyyMMddhhssmm.txt"), true, Encoding.GetEncoding("gb2312"));
保存的文件打不开 格式不不对呀 也不是txt格式呢

追答

应该是没问题的。你用记事本打开看看

温馨提示:内容为网友见解,仅供参考
第1个回答  2011-10-12
writer = new StreamWriter(path+DateTime.Now.ToString("yyyyMMddhhssmm")“+".txt“, true, Encoding.GetEncoding("gb2312"));
第2个回答  2011-10-23
建议去通信论坛看下
第3个回答  2011-10-12
要存什么,存成什么格式,你倒是说清呀追问

存的就是我采集上来的数据 TXT格式的文件就成 你QQ给我下 我加你

第4个回答  2011-10-12
这是plc上面的吗追问

我是在VS2008 环境 c# winform 里写的 一个串口通信 实时采集数据的一个程序