ProgramingTip

BinaryReader의 모든 바이트를 소비하는 우아한 방법?

bestdevel 2020. 11. 26. 19:39
반응형

BinaryReader의 모든 바이트를 소비하는 우아한 방법?


StreamReader.ReadToEnd방법 을 에뮬레이트하는 우아한 BinaryReader무릎 관절? 아마도 모든 바이트를 바이트 배열에 넣을 수 있습니까?

나는 관리한다 :

read1.ReadBytes((int)read1.BaseStream.Length);

...하지만 더 나은 방법이 될 것입니다.


간단하게 :

byte[] allData = read1.ReadBytes(int.MaxValue);

문서는 스트림의 도달에 도달 할 때까지 모든 바이트를 읽을 수 있습니다.


최신 정보

이 우아한 것, 그리고 문서 가이 실제 작동 할 것을 계획 할 것 같지만 구현 (.NET 2, 3.5 체크를하고, 4) 데이터의 전체 크기의 바이트 배열을 할당하는 것 OutOfMemoryException입니다. 32에-비트 시스템.

따라서 우아한 방법은 믿을 수 있고 싶습니다 .

대신 @iano의 답변에 대한 다음 변형을 권장합니다. 이 변형은 .NET 4에 의존하지 않는 언어에
대한 확장 방법을 만듭니다 BinaryReader(또는 Stream코드는 둘 중 하나에 대해 동일 함).

public static byte[] ReadAllBytes(this BinaryReader reader)
{
    const int bufferSize = 4096;
    using (var ms = new MemoryStream())
    {
        byte[] buffer = new byte[bufferSize];
        int count;
        while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
            ms.Write(buffer, 0, count);
        return ms.ToArray();
    }

}


BinaryReader 로이 작업을 수행 하는 쉬운 방법 은 없습니다 . 미리 읽어야하는 개수를 모르는 경우 MemoryStream을 사용하는 것이 좋습니다.

public byte[] ReadAllBytes(Stream stream)
{
    using (var ms = new MemoryStream())
    {
        stream.CopyTo(ms);
        return ms.ToArray();
    }
}

를 호출 할 때 추가 복사를 방지하기 ToArray()대신 비용을 Position지불 할 수 GetBuffer()있습니다.


스트림의 내용을 다른 복사하기 위해 파일 끝에 도달 할 때까지 "일부"바이트를 읽는 문제를 해결했습니다.

private const int READ_BUFFER_SIZE = 1024;
using (BinaryReader reader = new BinaryReader(responseStream))
{
    using (BinaryWriter writer = new BinaryWriter(File.Open(localPath, FileMode.Create)))
    {
        int byteRead = 0;
        do
        {
            byte[] buffer = reader.ReadBytes(READ_BUFFER_SIZE);
            byteRead = buffer.Length;
            writer.Write(buffer);
            byteTransfered += byteRead;
        } while (byteRead == READ_BUFFER_SIZE);                        
    }                
}

이 문제에 대한 또 다른 접근 방식은 C # 확장 방법을 사용하는 것입니다.

public static class StreamHelpers
{
   public static byte[] ReadAllBytes(this BinaryReader reader)
   {
      // Pre .Net version 4.0
      const int bufferSize = 4096;
      using (var ms = new MemoryStream())
      {
        byte[] buffer = new byte[bufferSize];
        int count;
        while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
            ms.Write(buffer, 0, count);
        return ms.ToArray();
      }

      // .Net 4.0 or Newer
      using (var ms = new MemoryStream())
      {
         stream.CopyTo(ms);
         return ms.ToArray();
      }
   }
}

이 접근 방식을 사용하면 코드를 다시 사용할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/8613187/an-elegant-way-to-consume-all-bytes-of-a-binaryreader

반응형