2014-01-24 80 views
1

我工作的RS232通信的努力,但已運行到與一些我處理陣列的問題。C#閱讀,存儲和組合陣列

在下面我發送出「命令」的意圖來讀取和前4個字節的命令的存儲在一個所謂的「FirstFour」新的數組的例子。對於每個正在運行的循環執行,我也希望將整數「i」轉換爲十六進制值。然後我打算在「FirstFour」和「iHex」陣列組合成一個新的數組記爲「ComboByte」。下面是我的代碼到目前爲止,但它似乎並沒有工作。

private void ReadStoreCreateByteArray() 
    { 
     byte[] Command = { 0x01, 0x02, 0x05, 0x04, 0x05, 0x06, 0x07, 0x08}; 

     for (int i = 0; i < 10; i++) 
     { 
      //Send Command 
      comport.Write(Command, 0, Command.Length); 

      //Read response and store in buffer 
      int bytes = comport.BytesToRead; 
      byte[] Buffer = new byte[bytes]; 
      comport.Read(Buffer, 0, bytes); 

      //Create 4 byte array to hold first 4 bytes out of Command 
      var FirstFour = Buffer.Take(4).ToArray(); 

      //Convert i to a Hex value 
      byte iHex = Convert.ToByte(i.ToString()); 

      //Combine "FirstFour" and "iHex" into a new array 
      byte [] ComboByte = {iHex, FirstFour[1], FirstFour[2], FirstFour[3], First Four[4]}; 
      comport.Write(ComboByte, 0, ComboByte.Length); 

     } 
    } 

任何幫助,將不勝感激。謝謝!

+0

'comport.Read(緩衝液,0,字節);'它是必不可少** **從'Read'正確處理返回方法,順便說一句。 –

+0

什麼是'respBuffer'? –

+0

ComboByte初始化是否正確? FirstFour不應該從0-3而不是1-4索引? –

回答

1

數組是從零開始的,所以......

byte [] ComboByte = {iHex, FirstFour[0], FirstFour[1], FirstFour[2], First Four[3]}; 

...應該給你FirstFour的前4個元素。

+0

感謝沒收 – Nevets

1

首先,您需要需要來處理來自Read操作的返回值。下面的模式應該可以正常工作了一系列的API,包括SerialPortStream等:

static void ReadExact(SerialPort port, byte[] buffer, int offset, int count) 
{ 
    int read; 
    while(count > 0 && (read = port.Read(buffer, offset, count)) > 0) 
    { 
     count -= read; 
     offset += read; 
    } 
    if (count != 0) throw new EndOfStreamException(); 
} 

所以:你有可以讀取的字節的可靠數的方法 - 你應該再能夠重新使用一個緩衝和順序來填充它:

byte[] buffer = new byte[5]; 
for (int i = 0; i < 10; i++) 
{ 

    //... 
    buffer[0] = (byte)i; 
    ReadExact(port, buffer, 1, 4); 
} 

BytesToRead屬性是除了決定是否同步或異步讀,因爲它不會告訴你更多的數據是否是迫在眉睫基本上無用。使用現有的代碼不能保證您至少有4個字節。