C# 二進位位元組流尋找函數IndexOf
/// <summary> /// 報告指定的 System.Byte[] 在此執行個體中的第一個匹配項的索引。 /// </summary> /// <param name="srcBytes">被執行尋找的 System.Byte[]。</param> /// <param name="searchBytes">要尋找的 System.Byte[]。</param> /// <returns>如果找到該位元組數組,則為 searchBytes 的索引位置;如果未找到該位元組數組,則為 -1。如果 searchBytes 為 null 或者長度為0,則傳回值為 -1。</returns> internal int IndexOf(byte[] srcBytes, byte[] searchBytes) { if (srcBytes == null) { return -1; } if (searchBytes == null) { return -1; } if (srcBytes.Length == 0) { return -1; } if (searchBytes.Length == 0) { return -1; } if (srcBytes.Length < searchBytes.Length) { return -1; } for (int i = 0; i < srcBytes.Length - searchBytes.Length; i++) { if (srcBytes[i] == searchBytes[0]) { if (searchBytes.Length == 1) { return i; } bool flag = true; for (int j = 1; j < searchBytes.Length; j++) { if (srcBytes[i + j] != searchBytes[j]) { flag = false; break; } } if (flag) { return i; } } } return -1; }
使用樣本:
receiveData = new byte[1024];int receiveLen = socket.ReceiveFrom(receiveData, ref ep);receiveData = this.SubByte(receiveData, 0, receiveLen); if (this.IndexOf(receiveData, System.Text.Encoding.Unicode.GetBytes("Exec_Exit")) != -1){ this.runing = false; break; }