DataTableReader.GetChars(Int32, Int64, Char[], Int32, Int32) Metodo

Definizione

Restituisce il valore della colonna specificata come stringa di caratteri.

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

Parametri

ordinal
Int32

Ordinale di colonna in base zero.

dataIndex
Int64

Indice all'interno del campo da cui avviare l'operazione di lettura.

buffer
Char[]

Buffer in cui scrivere il flusso di caratteri.

bufferIndex
Int32

Indice all'interno del buffer da cui iniziare a inserire i dati.

length
Int32

Lunghezza massima per la copia nel buffer.

Restituisce

Numero effettivo di caratteri letti.

Eccezioni

L'indice passato non rientrava nell'intervallo compreso tra 0 e FieldCount -1.

Si è tentato di recuperare dati da una riga eliminata.

È stato effettuato un tentativo di lettura o di accesso a una colonna in una classe DataTableReader chiusa.

La colonna specificata non contiene una matrice di caratteri.

Esempio

Nell'esempio seguente viene illustrato il GetChars metodo. Il TestGetChars metodo prevede che venga passato un DataTableReader riempimento con due colonne di dati: un nome file nella prima colonna e una matrice di caratteri nella seconda. Inoltre, TestGetChars consente di specificare le dimensioni del buffer da usare durante la lettura dei dati dalla matrice di caratteri in DataTableReader. TestGetChars crea un file corrispondente a ogni riga di dati nell'oggetto DataTableReader, usando i dati forniti nella prima colonna di DataTableReader come nome file.

Questa procedura illustra l'uso dei dati di lettura del GetChars metodo archiviati in DataTable come matrice di caratteri. Qualsiasi altro tipo di dati causa la GetChars creazione di un oggetto 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

Commenti

GetChars restituisce il numero di caratteri disponibili nel campo. La maggior parte del tempo è la lunghezza esatta del campo. Tuttavia, il numero restituito può essere minore della lunghezza effettiva del campo se è già stato usato il metodo GetChars per ottenere i caratteri del campo.

Il numero effettivo di caratteri letti può essere minore della lunghezza richiesta, se viene raggiunta la fine del campo. Se si passa un buffer null (Nothing in Visual Basic), GetChars restituisce la lunghezza dell'intero campo in caratteri, non le dimensioni rimanenti in base al parametro offset del buffer.

Non vengono eseguite conversioni; pertanto i dati da recuperare devono essere già una matrice di caratteri o una matrice di caratteri o una matrice di caratteri.

Si applica a