【发布时间】:2012-07-12 20:57:10
【问题描述】:
我遇到了一个小型 C# 应用程序的问题。 该应用程序必须通过串行端口连接到读取数据矩阵代码的条形码扫描仪。数据矩阵代码表示一个字节数组,它是一个 zip 存档。我阅读了很多关于 SerialPort.DataReceived 工作方式的信息,但我找不到一个优雅的解决方案来解决我的问题。并且该应用程序应与不同的条形码扫描仪一起使用,因此我无法使其特定于扫描仪。这是我的一些代码:
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 内容的整个字节集。您需要缓冲您阅读的内容。你需要知道你什么时候得到它们。这是您必须找出的东西,请仔细阅读条形码扫描仪手册。
标签: c# serial-port barcode-scanner