2012-08-04 11 views
0

문자열로 ID를 보내야하는 tcp it 서비스로 작업하려고합니다. 샘플 코드에서 아래 메소드가 있습니다. 나는 "4000", "2000", "3000"과 같은 4 개의 문자로 문자열을 입력 할 때 문제가 발생하지만, "4", "20"또는 "300" System.ArgumentException : 대상 배열이 충분하지 않았습니다.

System.ArgumentException : 대상 배열의 길이가 충분하지 않습니다. destIndex 및 length 및 배열의 ​​하한을 확인하십시오.

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 당신의 buff 당신이 원하는 4

크기 인 idb에 맞게 너무 작습니다, 단지 크기 3이다 id.CopyTo (buff, 1 + 1 + idb.Length); – user1576148

답변

0

나는 문제는 그것이 있어야 할 때 버퍼 길이가

1 + 1 + id.Length + l 

것을 의심

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

해고하는 것이 문제를 확인하는 가장 좋은 방법 디버거 및 buff의 길이를보십시오.

+0

문자열을 빈 문자열로 채우고 항상 4 문자로 지정하면 문제가 해결되는 것 같습니다. 'byte [] id = UTF8Encoding.UTF8.GetBytes (tId.PadRight (4, ''));' – user1576148

+0

@ user1576148'idb'는 거의 항상 4 바이트 길이이기 때문에 확실히 그럴 것입니다. 버퍼 길이를 결정할 때'idb'와'id' 길이를 사용하는 대신'id' 길이를 두 번 사용하는 이유가 있습니까? – ikh

0

idbid에서 buff까지만 복사 할 수 있습니다. 크기는 2*id.Length + 2입니다. 에서

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; 
    } 
관련 문제