System.ArgumentException:目标数组不够长

本文关键字:不够 数组 目标 ArgumentException System | 更新日期: 2024-10-24 19:20:27

我正在尝试使用一个tcp it服务,该服务要求我将ID作为字符串发送。我从一个示例代码中得到了下面的方法。问题是,当我输入包含4个字符的字符串时,如"4000"、"2000"、"3000",该方法有效,但当我输入的字符串包含少于4个字符"1"、"20"或"300"它返回

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;
    }

System.ArgumentException:目标数组不够长

我怀疑问题在于缓冲区长度是

1 + 1 + id.Length + l

什么时候应该是

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

检查这个问题的最好方法是启动调试器并查看buff的长度。

您正在将idbid复制到只有2*id.Length + 2大小的buff

因此,当id只有3号时,您的buff太小,无法容纳4号的idb

您想要:

byte[] buff = new byte[1 + 1 + id.Length + idb.Length];
    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;
    }