Reputation: 97
#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
Edited one. I tried sending 0xFF but the display in console is 0 for this code.
Hi. I have this code and after executing it, I have a problem with regards to this:
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.
and it is point in this line:
definition.buffering = BitConverter.ToInt64(buffer, 0);
How can I fix this?
Upvotes: 0
Views: 140
Reputation: 157118
I think your buffer's length is not (at least) 8.
MSDN says:
Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.
You get a ArgumentException
when:
startIndex is greater than or equal to the length of value minus 7, and is less than or equal to the length of value minus 1.
Before calling the BitConverter.ToInt64
method you should check that
serial.BytesToRead.Length >= 8
To go through all bytes try this:
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.
}
}
Upvotes: 4