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

Definicja

Zwraca wartość określonej kolumny jako tablicę znaków.

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

Parametry

ordinal
Int32

Liczba porządkowa kolumn opartych na zerach.

dataIndex
Int64

Indeks w polu, z którego ma rozpocząć operację odczytu.

buffer
Char[]

Bufor, do którego ma być odczytywany strumień znaków.

bufferIndex
Int32

Indeks w buforze, w którym należy rozpocząć umieszczanie danych.

length
Int32

Maksymalna długość kopiowania do buforu.

Zwraca

Rzeczywista liczba odczytanych znaków.

Wyjątki

Przekazany indeks był poza zakresem od 0 do FieldCount -1.

Podjęto próbę pobrania danych z usuniętego wiersza.

Podjęto próbę odczytu lub uzyskania dostępu do kolumny w zamkniętej DataTableReaderkolumnie .

Określona kolumna nie zawiera tablicy znaków.

Przykłady

W poniższym przykładzie pokazano metodę GetChars . Metoda TestGetChars oczekuje przekazania wypełnionej DataTableReader dwiema kolumnami danych: nazwą pliku w pierwszej kolumnie i tablicą znaków w drugiej. Ponadto umożliwia określenie rozmiaru buforu, TestGetChars który ma być używany podczas odczytywania danych z tablicy znaków w obiekcie DataTableReader. TestGetChars Tworzy plik odpowiadający każdemu wierszowi danych w DataTableReaderobiekcie przy użyciu podanych danych w pierwszej kolumnie elementu DataTableReader jako nazwy pliku.

Ta procedura przedstawia użycie GetChars metody odczytu danych przechowywanych w DataTable tablicy znaków. Każdy inny typ danych powoduje GetChars , że metoda zgłasza błąd 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

Uwagi

GetChars Zwraca liczbę dostępnych znaków w polu. W większości przypadków jest to dokładna długość pola. Jednak zwrócona liczba może być mniejsza niż rzeczywista długość pola, jeśli GetChars została już użyta do uzyskania znaków z pola.

Rzeczywista liczba odczytanych znaków może być mniejsza niż żądana długość, jeśli osiągnięto koniec pola. W przypadku przekazania buforu o wartości null (Nothing w Visual Basic) GetChars zwraca długość całego pola w znakach, a nie pozostałego rozmiaru na podstawie parametru przesunięcia buforu.

Nie są wykonywane żadne konwersje; w związku z tym dane do pobrania muszą być już tablicą znaków lub coercible do tablicy znaków.

Dotyczy