DataTableReader.GetBytes(Int32, Int64, Byte[], Int32, Int32) 메서드

정의

지정된 열 오프셋에서 시작하는 바이트 스트림을 지정된 버퍼 오프셋에서 시작하는 배열로 버퍼로 읽습니다.

public:
 override long GetBytes(int ordinal, long dataIndex, cli::array <System::Byte> ^ buffer, int bufferIndex, int length);
public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length);
override this.GetBytes : int * int64 * byte[] * int * int -> int64
Public Overrides Function GetBytes (ordinal As Integer, dataIndex As Long, buffer As Byte(), bufferIndex As Integer, length As Integer) As Long

매개 변수

ordinal
Int32

0부터 시작하는 열 서수입니다.

dataIndex
Int64

읽기 작업을 시작할 필드 내의 인덱스입니다.

buffer
Byte[]

바이트 스트림을 읽을 버퍼입니다.

bufferIndex
Int32

데이터 배치를 시작할 버퍼 내의 인덱스입니다.

length
Int32

버퍼에 복사할 최대 길이입니다.

반품

읽은 실제 바이트 수입니다.

예외

전달된 인덱스가 0에서 1까지 FieldCount 의 범위를 벗어났습니다.

삭제된 행에서 데이터를 검색하려고 했습니다.

닫힌 DataTableReader열의 열을 읽거나 액세스하려고 했습니다.

지정된 열에 바이트 배열이 없습니다.

예제

다음 예제에서는 AdventureWorks 샘플 데이터베이스에서 데이터를 기반으로 만들고 DataTableReader 검색된 각 이미지를 C:\ 폴더의 별도 파일에 저장합니다. 이 애플리케이션을 테스트하려면 새 콘솔 애플리케이션을 만들고, System.Drawing.dll 어셈블리를 참조하고, 샘플 코드를 새로 만든 파일에 붙여넣습니다.

using System;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        TestGetBytes();
    }

    static private void TestGetBytes()
    {
        // Set up the data adapter, using information from
        // the AdventureWorks sample database.
        SqlDataAdapter photoAdapter = SetupDataAdapter(
            "SELECT ThumbnailPhotoFileName, ThumbNailPhoto " +
            "FROM Production.ProductPhoto");
        // Fill the DataTable.
        DataTable photoDataTable = new DataTable();
        photoAdapter.Fill(photoDataTable);

        using (DataTableReader reader = new DataTableReader(photoDataTable))
        {
            while (reader.Read())
            {
                String productName = null;
                try
                {
                    // Get the name of the file.
                    productName = reader.GetString(0);
                    // Get the length of the field. Pass null
                    // in the buffer parameter to retrieve the length
                    // of the data field. Ensure that the field isn't
                    // null before continuing.
                    if (reader.IsDBNull(1))
                    {
                        Console.WriteLine(productName + " is unavailable.");
                    }
                    else
                    {
                        long len = reader.GetBytes(1, 0, null, 0, 0);
                        // Create a buffer to hold the bytes, and then
                        // read the bytes from the DataTableReader.
                        Byte[] buffer = new Byte[len];
                        reader.GetBytes(1, 0, buffer, 0, (int)len);
                        // Create a new Bitmap object, passing the array
                        // of bytes to the constructor of a MemoryStream.
                        using (Bitmap productImage = new
                                   Bitmap(new MemoryStream(buffer)))
                        {
                            String fileName = "C:\\" + productName;
                            // Save in gif format.
                            productImage.Save(fileName, ImageFormat.Gif);
                            Console.WriteLine("Successfully created " + fileName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(productName + ": " + ex.Message);
                }
            }
        }
        Console.WriteLine("Press Enter to finish.");
        Console.ReadLine();
    }

    static private SqlDataAdapter SetupDataAdapter(String sqlString)
    {
        // Assuming all the default settings, create a SqlDataAdapter
        // working with the AdventureWorks sample database that's
        // available with SQL Server.
        String connectionString =
            "Data Source=(local);Initial Catalog=AdventureWorks;" +
            "Integrated Security=true";
        return new SqlDataAdapter(sqlString, connectionString);
    }
}
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Imaging
    
Module Module1
   Sub Main()
      TestGetBytes()
   End Sub
   Private Sub TestGetBytes()
         ' Set up the data adapter, using information from 
      ' the AdventureWorks sample database.
      Dim photoAdapter As SqlDataAdapter = _
         SetupDataAdapter("SELECT ThumbnailPhotoFileName, " & _
         "ThumbNailPhoto FROM Production.ProductPhoto")

      ' Fill the DataTable.
      Dim photoDataTable As New DataTable
      photoAdapter.Fill(photoDataTable)

      ' Create the DataTableReader.
      Using reader As DataTableReader = New DataTableReader(photoDataTable)

         Dim buffer() As Byte
         Dim productName As String
         While reader.Read()
            Try
               ' Get the name of the file.
               productName = reader.GetString(0)

               ' Get the length of the field. Pass Nothing
               ' in the buffer parameter to retrieve the length
               ' of the data field. Ensure that the field isn't 
               ' null before continuing.
               If reader.IsDBNull(1) Then
                  Console.WriteLine( _
                     productName & " is unavailable.")
               Else
                  ' Retrieve the length of the necessary byte array.
                  Dim len As Long = reader.GetBytes(1, 0, Nothing, 0, 0)
                  ' Create a buffer to hold the bytes, and then 
                  ' read the bytes from the DataTableReader.
                  ReDim buffer(CInt(len))
                  reader.GetBytes(1, 0, buffer, 0, CInt(len))

                  ' Create a new Bitmap object, passing the array
                  ' of bytes to the constructor of a MemoryStream.
                  Using productImage As New Bitmap(New MemoryStream(buffer))
                     Dim fileName As String = "C:\" & productName
                     ' Save in gif format.
                     productImage.Save( _
                      fileName, ImageFormat.Gif)
                     Console.WriteLine("Successfully created " & _
                        fileName)
                  End Using
               End If
            Catch ex As Exception
               Console.WriteLine(productName & ": " & _
                  ex.Message)
            End Try
         End While
      End Using
      Console.WriteLine("Press Enter to finish.")
      Console.ReadLine()
   End Sub

   Private Function SetupDataAdapter( _
      ByVal sqlString As String) As SqlDataAdapter
      ' Assuming all the default settings, create a SqlDataAdapter
      ' working with the AdventureWorks sample database that's 
      ' available with SQL Server.
      Dim connectionString As String = _
         "Data Source=(local);" & _
         "Initial Catalog=AdventureWorks;" & _
         "Integrated Security=true"
      Return New SqlDataAdapter(sqlString, connectionString)
   End Function
End Module

설명

GetBytes 는 필드에서 사용 가능한 바이트 수를 반환합니다. 대부분의 경우 필드의 정확한 길이입니다. 그러나 반환된 숫자는 필드에서 바이트를 가져오는 데 이미 사용된 경우 GetBytes 필드의 실제 길이보다 작을 수 있습니다. 예를 들어 DataTableReader 큰 데이터 구조를 버퍼로 읽는 경우와 같은 경우가 있을 수 있습니다.

null(Visual Basic Nothing)인 버퍼를 전달하면 GetBytes 버퍼 오프셋 매개 변수에 따라 나머지 크기가 아니라 전체 필드의 길이를 바이트 단위로 반환합니다.

변환은 수행되지 않습니다. 따라서 검색된 데이터는 이미 바이트 배열이거나 바이트 배열로 강제 변환할 수 있어야 합니다.

적용 대상

추가 정보