我遇到了一个小型C#应用程序的问题。 应用程序必须通过串行端口连接到读取Data Matrix代码的条形码扫描器。 Data Matrix代码表示一个zip文档的字节数组。我读了很多关于SerialPort.DataReceived的工作方式,但我找不到解决我的问题的优雅方案。该应用程序应该与不同的条形码扫描仪一起工作,所以我不能使它成为扫描仪特定的。这里是我的一些代码:C#串行端口通信问题
using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using Ionic.Zip;
namespace SIUI_PE
{
public partial class Form1 : Form
{
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
return;
}
_serialPort.Handshake = Handshake.None;
_serialPort.ReadBufferSize = 10000;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
_serialPort.Open();
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[10000];
_serialPort.Read(data, 0, 10000);
File.WriteAllBytes(Directory.GetCurrentDirectory() + "/temp/fis.zip", data);
try
{
using (ZipFile zip = ZipFile.Read(Directory.GetCurrentDirectory() + "/temp/fis.zip"))
{
foreach (ZipEntry ZE in zip)
{
ZE.Extract(Directory.GetCurrentDirectory() + "/temp");
}
}
File.Delete(Directory.GetCurrentDirectory() + "/temp/fis.zip");
}
catch (Exception ex1)
{
MessageBox.Show("Corrupt Archive: " + ex1.ToString());
}
}
}
}
所以我的问题是:我怎么知道我读了扫描仪发送的所有字节?
的文档的核心问题是您_serialPort.Read()调用。它有一个你不能忽视的返回值。它将*不*为10000,然而在您调用它时会收到很多字节。这通常是一对夫妇,当然不是组成.zip内容的整个字节集合。你需要缓冲你读的东西。而且你需要知道你什么时候得到它们。这是你必须找到的东西,仔细阅读条码扫描仪手册。 – 2012-07-12 21:32:34