DataTableReader.GetBytes(Int32, Int64, Byte[], Int32, Int32) Método

Definición

Lee una secuencia de bytes que comienza en la posición de desplazamiento de la columna especificada cargándola al búfer como una matriz, comenzando a cargar desde la posición de desplazamiento de búfer especificada.

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);
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

Parámetros

ordinal
Int32

Índice de la columna de base cero.

dataIndex
Int64

Índice del campo a partir del cual se va a comenzar la operación de lectura.

buffer
Byte[]

Búfer en el que se va a leer la secuencia de bytes.

bufferIndex
Int32

Índice en el búfer en el que se van a comenzar a colocar los datos.

length
Int32

Longitud máxima que se puede copiar en el búfer.

Devoluciones

El número real de bytes que se leen.

Excepciones

El índice que se ha pasado se encontraba fuera del intervalo entre 0 y FieldCount - 1.

Se ha intentado recuperar los datos de una fila eliminada.

Se ha intentado la lectura o el acceso a una columna en un objeto DataTableReader cerrado.

La columna especificada no contiene una matriz de bytes.

Ejemplos

En el ejemplo siguiente se crea un DataTableReader elemento basado en los datos de la base de datos de ejemplo AdventureWorks y se guarda cada imagen recuperada en un archivo independiente en la carpeta C:\. Para probar esta aplicación, cree una nueva aplicación de consola, haga referencia al ensamblado System.Drawing.dll y pegue el código de ejemplo en el archivo recién creado.

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

Comentarios

GetBytes devuelve el número de bytes disponibles en el campo . La mayoría de las veces es la longitud exacta del campo. Sin embargo, el número devuelto puede ser menor que la longitud verdadera del campo si GetBytes ya se ha usado para obtener bytes del campo. Este puede ser el caso, por ejemplo, cuando está DataTableReader leyendo una estructura de datos grande en un búfer

Si pasa un búfer que es null (Nothing en Visual Basic), GetBytes devuelve la longitud de todo el campo en bytes, no el tamaño restante en función del parámetro de desplazamiento del búfer.

No se realizan conversiones; Por lo tanto, los datos recuperados ya deben ser una matriz de bytes o coercible para una matriz de bytes.

Se aplica a

Consulte también