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

Definição

Devolve o valor da coluna especificada como um array 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);
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

O ordinal da coluna baseada em zero.

dataIndex
Int64

O índice dentro do campo a partir do qual iniciar a operação de leitura.

buffer
Char[]

O buffer para ler o fluxo de caracteres.

bufferIndex
Int32

O índice dentro do buffer onde começar a colocar os dados.

length
Int32

O comprimento máximo para copiar para o buffer.

Devoluções

O número real de caracteres lidos.

Exceções

O índice aprovado estava fora do intervalo de 0 a FieldCount - 1.

Foi feita uma tentativa de recuperar dados de uma linha eliminada.

Foi feita uma tentativa de ler ou aceder a uma coluna num arquivo fechado DataTableReader.

A coluna especificada não contém um array de caracteres.

Exemplos

O exemplo seguinte demonstra o GetChars método. O TestGetChars método espera ser preenchido DataTableReader com duas colunas de dados: um nome de ficheiro na primeira coluna e um array de caracteres na segunda. Além disso, TestGetChars permite-lhe especificar o tamanho do buffer a usar enquanto lê os dados do array de caracteres no DataTableReaderarquivo . TestGetChars cria um ficheiro correspondente a cada linha de dados no DataTableReader, usando os dados fornecidos na primeira coluna do DataTableReader como nome do ficheiro.

Este procedimento demonstra a utilização do GetChars método de leitura de dados que estavam armazenados DataTable no como um array de caracteres. Qualquer outro tipo de dado faz com que o GetChars método execute um InvalidCastException.

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

Observações

GetChars devolve o número de caracteres disponíveis no campo. Na maioria das vezes, este é exatamente o comprimento do campo. No entanto, o número devolvido pode ser inferior ao comprimento real do campo se GetChars já tiver sido usado para obter caracteres do campo.

O número real de caracteres lidos pode ser inferior ao comprimento solicitado, se o fim do campo for atingido. Se passares um buffer que é nulo (Nothing em Visual Basic), GetChars devolve o comprimento de todo o campo em caracteres, e não o tamanho restante baseado no parâmetro de offset do buffer.

Não são realizadas conversões; portanto, os dados a recuperar devem já ser um array de caracteres ou coercíveis para um array de caracteres.

Aplica-se a