binary read
普通にバッファサイズをおもいっきりとって一回読むのでもいいのかなー
public static byte[] GetData( this Stream input, int size ) { byte[] buffer = new byte[Math.Min( 1024, size )]; int totalSize = 0; using ( MemoryStream ms = new MemoryStream() ) { int readSize; while ( totalSize < size && ( ( readSize = input.Read( buffer, 0, GetBuffSize( buffer, size, totalSize ) ) ) > 0 ) ) { ms.Write( buffer, 0, readSize ); totalSize += readSize; } if ( totalSize != size ) { throw new IOException( "Cannot read the size specified." ); } return ms.ToArray(); } } private static int GetBuffSize( byte[] buffer, int size, int totalSize ) { return Math.Min( buffer.Length, size - totalSize ); }
終了処理をsizeでなくてreadsizeが0のみで判断すればBinaryのReadToEndになる
public static byte[] ReadToEnd( this Stream input ) { byte[] buffer = new byte[ 1024 ]; using ( MemoryStream ms = new MemoryStream() ) { int readSize; while ( ( readSize = input.Read( buffer, 0, buffer.Length ) ) > 0 ) { ms.Write( buffer, 0, readSize ); } return ms.ToArray(); } }