2014-02-27 69 views
0
#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

错误听起来很翔实给我。 '缓冲区'的长度是多少? –

+0

因此,员工的名字只是字节缓冲区中的一个字节?你确定要迭代通过串口收到的所有字节吗? –

回答

4

我觉得你的缓冲区的长度不是(至少)8

MSDN说:

Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.

你得到了ArgumentException时:

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.

调用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. 
    } 
} 
+0

是的。也许这就是问题所在。但如果它大于8,我怎样才能将16位分成8位? – iaskyou

+0

在其他方面应该怎么样?如果我有16位?我怎么能提取2个字节,并存储在缓冲区[0]和缓冲区[1] – iaskyou

+0

@iaskyou:代码为你做这个。在“if”的第一个分支中,您必须处理每个“Int64”。在'else'中只有不好的结果(例如当你有20个字节时,你有4个太多) –