您的位置:首页 > 编程语言 > C#

c# 读取串口——如何全部读取

2010-02-05 16:24 204 查看
public byte[] Read()
{
byte[] inbuffer = null;
if (serialPort.IsOpen && serialPort.BytesToRead > 0)
{
try
{
inbuffer = new byte[serialPort.BytesToRead];
serialPort.Read(inbuffer, 0, serialPort.BytesToRead);
string strRaad = ASCIIEncoding.ASCII.GetString(inbuffer, 0, inbuffer.Length);

while (strRaad.Contains(serialPort.NewLine))
{
Thread.Sleep(800);
if (serialPort.BytesToRead == 0)
break;
byte[] temp = inbuffer;
byte[] inbuffer2 = new byte[serialPort.BytesToRead];

serialPort.Read(inbuffer2, 0, serialPort.BytesToRead);
inbuffer = new byte[inbuffer.Length + inbuffer2.Length];

temp.CopyTo(inbuffer, 0);
inbuffer2.CopyTo(inbuffer, temp.Length);
strRaad = ASCIIEncoding.ASCII.GetString(inbuffer, 0, inbuffer.Length);
}
}
catch
{
}
}
return inbuffer;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# byte string null