2010-12-08 3 views
2

MySQL 5.0 Connector.NET Examples 상태 :MySQL의 .NET 커넥터 문서 혼란

GetBytes는 현장에서 사용할 수있는 바이트 수를 돌려줍니다. 대부분의 경우 이것이 필드의 정확한 길이입니다.

그러나 MySQL 5.0 Connector.NET DocumentationGetBytes의 반환 값을 버퍼에 읽은 바이트 수로 나열합니다.

나에게 이것은 전혀 다른 것이 아닙니다!

내 질문은 무엇입니까 : MemoryStream 개체로 데이터 원본의 콘텐츠를 가져 오는 가장 읽기 쉬운 구조는 무엇입니까? GetBytes에서 반환 값을 사용하여 GetBytes 메서드의 데이터 인덱스 매개 변수를 증가 시키지만, 겉으로보기에는 필드를 오버런하는 것은 계속 발생합니다. IndexOutOfRangeException이 던져지기 때문입니다.

+0

다음과 같은 좋은 질문은 삭제하지 마십시오. http://stackoverflow.com/q/7570740/650492 – Johan

답변

4

나는 MySqlDataReader에 대한 설명서가 많이 남아 있다는 데 동의합니다.

nullbuffer 인수로 전달하면 GetBytes은 필드의 총 길이를 반환합니다. NULL이 아닌 buffer 인수를 전달하면 GetBytes은 버퍼에 기록 된 바이트 수를 반환합니다.

long length = yourReader.GetBytes(columnOrdinal, 0, null, 0, 0); 
long offset = 0; 
var buffer = new byte[4 * 1024]; // 4KB buffer 
var ms = new MemoryStream(); 

while (length > 0) 
{ 
    long bytesRead = yourReader.GetBytes(columnOrdinal, offset, buffer, 0, 
             (int)Math.Min(length, buffer.Length)); 

    if (bytesRead > 0) 
    { 
     ms.Write(buffer, 0, (int)bytesRead); 
     length -= bytesRead; 
     offset += bytesRead; 
    } 
} 
0

필자는 루크의 코드를 약간 수정했다 (그리고 upvoted). 더 나은, 그냥 다른 말을하지 않습니다. 2GB 미만의 필드에서만 작동합니다.

private static byte[] ReadBinaryField(MySqlDataReader reader, int fieldIndex) 
{ 
    var remaining = (int)reader.GetBytes(fieldIndex, 0, null, 0, 0); 
    var bytes = new byte[remaining]; 

    while (remaining > 0) 
    { 
     var offset = bytes.Length - remaining; 
     var bytesRead = (int)reader.GetBytes(fieldIndex, offset, bytes, offset, remaining); 
     if (bytesRead == 0) 
     { 
      // Hopefully this is impossible 
      throw new Exception("Could not read the rest of the field."); 
     } 
     remaining -= bytesRead; 
    } 
    return bytes; 
} 

원하는 경우 확장 방법을 사용할 수 있습니다.