Splitting a byte[] into multiple byte[] arrays in C#

前端 未结 4 1978
天涯浪人
天涯浪人 2020-12-09 21:51

I am trying to \"chunk\" up the bytes of an image. This will allow me to upload a large image in portions. I have the image currently stored as one large byte[]. I would lik

4条回答
  •  死守一世寂寞
    2020-12-09 22:33

    I wrote an extension for this, originally for strings, but decided to make it generic.

        public static T[] CopySlice(this T[] source, int index, int length, bool padToLength = false)
        {
            int n = length;
            T[] slice = null;
    
            if (source.Length < index + length)
            {
                n = source.Length - index;
                if (padToLength)
                {
                    slice = new T[length];
                }
            }
    
            if(slice == null) slice = new T[n];
            Array.Copy(source, index, slice, 0, n);
            return slice;
        }
    
        public static IEnumerable Slices(this T[] source, int count, bool padToLength = false)
        {
            for (var i = 0; i < source.Length; i += count)
                yield return source.CopySlice(i, count, padToLength);
        }
    

    Basically, you can use it like so:

    byte[] myBytes; // original byte array
    
    foreach(byte[] copySlice in myBytes.Slices(10))
    {
        // do something with each slice
    }
    

    Edit: I also provided an answer on SO using Buffer.BlockCopy here but BlockCopy will only work on byte[] arrays, so a generic version for strings wouldn't be possible.

提交回复
热议问题