////// 截取位元組陣列 /// /// 來源陣列 /// 起始索引 /// 截取長度 ///截取後的新陣列 public byte[] SubByte(byte[] srcBytes, int startIndex, int length) { System.IO.MemoryStream bufferStream = new System.IO.MemoryStream(); byte[] returnByte = new byte[] { }; if (srcBytes == null) return returnByte; if (startIndex < 0) startIndex = 0; if (startIndex < srcBytes.Length) { if (length < 1 || length > srcBytes.Length - startIndex) length = srcBytes.Length - startIndex; bufferStream.Write(srcBytes, startIndex, length); returnByte = bufferStream.ToArray(); bufferStream.SetLength(0); bufferStream.Position = 0; } bufferStream.Close(); bufferStream.Dispose(); return returnByte; }
使用 MemoryStream 寫入指定範圍並轉為陣列回傳,含參數驗證與資源釋放。