2012-08-04 90 views
0

我正在尝试使用tcp it服务,需要我以字符串形式发送一个ID。我从示例代码中获得了以下方法。 我的问题是,当我输入4个字符的数字,如“4000”,“2000”,“3000”字符串的方法工作,但当我输入字符串少于4个字符“1”,“20”或“300” 它返回System.ArgumentException:目标数组不够长

System.ArgumentException:目标数组不够长。检查 destIndex和长度以及数组的下限。

public byte[] prepNetworkStreamBuffer(string reqiiredID) { 
     byte[] id = UTF8Encoding.UTF8.GetBytes(reqiiredID); 
     int l = id.Length; 
     byte[] idb = BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder(l)); 

     byte[] buff = new byte[1 + 1 + id.Length + l]; 
     buff[0] = 0; 
     buff[1] = (byte)VerificationServiceCommands.addIDtoAFIS; 
     idb.CopyTo(buff, 1 + 1); 
     id.CopyTo(buff, 1 + 1 + idb.Length); 

     return buff; 
    } 
+0

在异常occors: id.CopyTo(buff,1 + 1 + idb.Length); – user1576148 2012-08-04 14:15:07

回答

0

我怀疑的问题是,缓冲区长度为

1 + 1 + id.Length + l 

当它应该是

1 + 1 + idb.Length + l 
     ^^^ 

来检查这个问题会火起来的最佳途径调试器并看看buff的长度。

+0

通过使用空字符串填充字符串并确保其始终为4个字符,似乎可以解决问题。 'byte [] id = UTF8Encoding.UTF8.GetBytes(tId.PadRight(4,''));' – user1576148 2012-08-04 14:41:52

+0

@ user1576148这肯定会是这样,因为'idb'几乎总是四个字节长。当确定缓冲区长度时,为什么你使用'id'的长度而不是使用'idb'和'id'的长度是否有原因? – ikh 2012-08-04 14:47:00

0

您正在复制idbidbuff,其尺寸只有2*id.Length + 2

所以当id只有大小为3,你的buff是太小,放不下idb,这是大小的4

你想:

byte[] buff = new byte[1 + 1 + id.Length + idb.Length]; 
0
public static bool TryGetArray(ref SomeObject[] source) 
    { 
     try 
     { 
      var localSource = new List<SomeObject>{new SomeObject(), new SomeObject()}; 

      var temp = new SomeObject[localSource.Count + source.Length]; 
      Array.Copy(source, temp, source.Length); 
      Array.ConstrainedCopy(localSource.ToArray(), 0, temp, source.Length, localSource.Count); 
      source = temp; 
     } 
     catch 
     { 
      return false; 
     } 
     return true; 
    }