DataTableReader.GetBytes(Int32, Int64, Byte[], Int32, Int32) Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Lee un flujo de bytes a partir del desplazamiento de columna especificado en el búfer como una matriz que comienza en el desplazamiento del búfer especificado.
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
Parámetros
- ordinal
- Int32
Ordinal de columna de base cero.
- dataIndex
- Int64
Índice dentro del campo desde el que se va a iniciar la operación de lectura.
- buffer
- Byte[]
Búfer en el que se va a leer el flujo de bytes.
- bufferIndex
- Int32
Índice dentro del búfer en el que se van a empezar a colocar los datos.
- length
- Int32
Longitud máxima que se va a copiar en el búfer.
Devoluciones
Número real de bytes leídos.
Excepciones
El índice pasado estaba fuera del intervalo de 0 a FieldCount - 1.
Se intentó recuperar datos de una fila eliminada.
Se intentó leer o tener acceso a una columna en un objeto cerrado DataTableReader.
La columna especificada no contiene una matriz de bytes.
Ejemplos
En el ejemplo siguiente se crea un DataTableReader basado en los datos de la base de datos de ejemplo AdventureWorks y se guarda cada imagen recuperada en un archivo independiente de 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. Esto 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 del campo completo en bytes, no el tamaño restante basado en el parámetro de desplazamiento del búfer.
No se realiza ninguna conversión; Por lo tanto, los datos recuperados ya deben ser una matriz de bytes o coercible en una matriz de bytes.