#region Receiving
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serial.BytesToRead;
byte[] buffer = new byte[bytes];
serial.Read(buffer, 0, bytes);
int length = buffer.Length;
for (int i = 0; i < length; i += 8)
{
if (length - i >= 8)
{
definition.buffering = BitConverter.ToInt64(buffer, i);
Console.Write(definition.buffering.ToString());
//Int64 val = BitConverter.ToInt64(buffer, i);
foreach (var item in buffer)
{
SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
//open connection to database
try
{
string itemcode = item.ToString();
sqliteCon.Open();
string Query = "insert into EmployeeList (empID,Name,surname,Age) values('" + itemcode + "','" + itemcode + "','" + itemcode + "','" + itemcode + "')";
SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
createCommand.ExecuteNonQuery();
MessageBox.Show("Saved");
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Console.Write(item.ToString());
}
}
else
{
// invalid (last) part.
}
}
//definition.buffering = BitConverter.ToInt64(buffer, 0);
Console.WriteLine();
Console.WriteLine(definition.buffering);
Console.WriteLine();
Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
thread.Start();
thread.Join();
}
#endregion
编辑一个。我尝试发送0xFF,但是此代码中控制台的显示为0。
您好。我有这个代码,执行后,我有一个问题:
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Destination array is not long enough to copy all the items in the collection. Check array index and length.
这就是这一点:
definition.buffering = BitConverter.ToInt64(buffer, 0);
我该如何解决这个问题?
答案 0 :(得分:4)
我认为你的缓冲区长度不是(至少)8。
MSDN说:
返回在字节数组中指定位置从八个字节转换的64位有符号整数。
在以下情况下获得ArgumentException
:
startIndex大于或等于值的长度减去7,并且小于或等于值的长度减去1。
在调用BitConverter.ToInt64
方法之前,您应该检查
serial.BytesToRead.Length >= 8
要浏览所有字节,请尝试以下操作:
int length = buffer.Length;
for (int i = 0; i < length; i += 8)
{
if (length - i >= 8)
{
Int64 val = BitConverter.ToInt64(buffer, i);
}
else
{
// invalid (last) part.
}
}