DataTableReader.GetChars(Int32, Int64, Char[], Int32, Int32) Método

Definición

Devuelve el valor de la columna especificada como una matriz de caracteres.

public:
 override long GetChars(int ordinal, long dataIndex, cli::array <char> ^ buffer, int bufferIndex, int length);
public override long GetChars (int ordinal, long dataIndex, char[]? buffer, int bufferIndex, int length);
public override long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length);
override this.GetChars : int * int64 * char[] * int * int -> int64
Public Overrides Function GetChars (ordinal As Integer, dataIndex As Long, buffer As Char(), 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
Char[]

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

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

Número real de caracteres 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 caracteres.

Ejemplos

En el siguiente ejemplo se muestra el GetChars método. El TestGetChars método espera pasar un DataTableReader relleno con dos columnas de datos: un nombre de archivo en la primera columna y una matriz de caracteres en el segundo. Además, TestGetChars permite especificar el tamaño del búfer que se va a usar a medida que lee los datos de la matriz de caracteres de DataTableReader. TestGetChars crea un archivo correspondiente a cada fila de datos de DataTableReader, utilizando los datos proporcionados en la primera columna de como nombre de DataTableReader archivo.

Este procedimiento muestra el uso del método de lectura de GetChars datos almacenados en DataTable como una matriz de caracteres. Cualquier otro tipo de datos hace que el GetChars método produzca una InvalidCastExceptionexcepción .

using System;
using System.Data;
using System.IO;

class Class1
{
    static void Main()
    {
        DataTable table = new DataTable();
        table.Columns.Add("FileName", typeof(string));
        table.Columns.Add("Data", typeof(char[]));
        table.Rows.Add(new object[] { "File1.txt", "0123456789ABCDEF".ToCharArray() });
        table.Rows.Add(new object[] { "File2.txt", "0123456789ABCDEF".ToCharArray() });

        DataTableReader reader = new DataTableReader(table);
        TestGetChars(reader, 7);
    }

    private static void TestGetChars(DataTableReader reader, int bufferSize)
    {
        // The filename is in column 0, and the contents are in column 1.
        const int FILENAME_COLUMN = 0;
        const int DATA_COLUMN = 1;

        char[] buffer;
        long offset;
        int charsRead = 0;
        string fileName;
        int currentBufferSize = 0;

        while (reader.Read())
        {
            // Reinitialize the buffer size and the buffer itself.
            currentBufferSize = bufferSize;
            buffer = new char[bufferSize];
            // For each row, write the data to the specified file.
            // First, verify that the FileName column isn't null.
            if (!reader.IsDBNull(FILENAME_COLUMN))
            {
                // Get the file name, and create a file with
                // the supplied name.
                fileName = reader.GetString(FILENAME_COLUMN);
                // Start at the beginning.
                offset = 0;

                using (StreamWriter outputStream =
                           new StreamWriter(fileName, false))
                {
                    try
                    {
                        // Loop through all the characters in the input field,
                        // incrementing the offset for the next time. If this
                        // pass through the loop reads characters, write them to
                        // the output stream.
                        do
                        {
                            charsRead = (int)reader.GetChars(DATA_COLUMN, offset,
                                buffer, 0, bufferSize);
                            if (charsRead > 0)
                            {
                                outputStream.Write(buffer, 0, charsRead);
                                offset += charsRead;
                            }
                        } while (charsRead > 0);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(fileName + ": " + ex.Message);
                    }
                }
            }
        }
        Console.WriteLine("Press Enter key to finish.");
        Console.ReadLine();
    }
}
Imports System.Data
Imports System.IO

Module Module1

   Private Sub TestGetChars( _
      ByVal reader As DataTableReader, ByVal bufferSize As Integer)

      ' The filename is in column 0, and the contents are in column 1.
      Const FILENAME_COLUMN As Integer = 0
      Const DATA_COLUMN As Integer = 1

      Dim buffer() As Char
      Dim offset As Integer
      Dim charsRead As Integer
      Dim fileName As String
      Dim currentBufferSize As Integer

      While reader.Read
         ' Reinitialize the buffer size and the buffer itself.
         currentBufferSize = bufferSize
         ReDim buffer(bufferSize - 1)

         ' For each row, write the data to the specified file.

         ' First, verify that the FileName column isn't null.
         If Not reader.IsDBNull(FILENAME_COLUMN) Then
            ' Get the file name, and create a file with 
            ' the supplied name.
            fileName = reader.GetString(FILENAME_COLUMN)

            ' Start at the beginning.
            offset = 0

            Using outputStream As New StreamWriter(fileName, False)
               Try

                  ' Loop through all the characters in the input field,
                  ' incrementing the offset for the next time. If this
                  ' pass through the loop reads characters, write them to 
                  ' the output stream.
                  Do
                     charsRead = Cint(reader.GetChars(DATA_COLUMN, offset, _
                        buffer, 0, bufferSize))
                     If charsRead > 0 Then
                        outputStream.Write(buffer, 0, charsRead)
                        offset += charsRead
                     End If
                  Loop While charsRead > 0
               Catch ex As Exception
                  Console.WriteLine(fileName & ": " & ex.Message)
               End Try
            End Using
         End If
      End While
      Console.WriteLine("Press Enter key to finish.")
      Console.ReadLine()
   End Sub

   Sub Main()
      Dim table As New DataTable
      table.Columns.Add("FileName", GetType(System.String))
      table.Columns.Add("Data", GetType(System.Char()))
      table.Rows.Add("File1.txt", "0123456789ABCDEF".ToCharArray)
      table.Rows.Add("File2.txt", "0123456789ABCDEF".ToCharArray)

      Dim reader As New DataTableReader(table)
      TestGetChars(reader, 7)
   End Sub
End Module

Comentarios

GetChars devuelve el número de caracteres disponibles en el campo. La mayoría de las veces es la longitud exacta del campo. Sin embargo, el valor devuelto puede ser menor que la longitud real del campo si GetChars ya se usó para obtener caracteres del campo.

El número real de caracteres leído puede ser menor que la longitud solicitada, si se alcanza el final del campo. Si pasa un búfer que es null (Nothing en Visual Basic), GetChars devuelve la longitud del campo completo en caracteres, 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 que se van a recuperar ya deben ser una matriz de caracteres o coercible para una matriz de caracteres.

Se aplica a