DataTableReader.GetChars(Int32, Int64, Char[], Int32, Int32) 메서드

정의

지정된 열의 값을 문자 배열로 반환합니다.

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

매개 변수

ordinal
Int32

0부터 시작하는 열 서수입니다.

dataIndex
Int64

읽기 작업을 시작할 필드 내의 인덱스입니다.

buffer
Char[]

문자 스트림을 읽을 버퍼입니다.

bufferIndex
Int32

데이터 배치를 시작할 버퍼 내의 인덱스입니다.

length
Int32

버퍼에 복사할 최대 길이입니다.

반품

읽은 실제 문자 수입니다.

예외

전달된 인덱스가 0에서 1까지 FieldCount 의 범위를 벗어났습니다.

삭제된 행에서 데이터를 검색하려고 했습니다.

닫힌 DataTableReader열의 열을 읽거나 액세스하려고 했습니다.

지정된 열에 문자 배열이 없습니다.

예제

다음 예제에서는 메서드를 보여 줍니다 GetChars . 메서드는 TestGetChars 데이터 열 2개(첫 번째 열의 파일 이름 및 두 번째 열의 문자 배열)로 채워진 형식으로 전달 DataTableReader 되어야 합니다. 또한 TestGetChars 에 있는 문자 배열 DataTableReader에서 데이터를 읽을 때 사용할 버퍼 크기를 지정할 수 있습니다. TestGetChars 는 파일 이름으로 첫 번째 열에 제공된 데이터를 사용하여 각 데이터 DataTableReader행에 DataTableReader 해당하는 파일을 만듭니다.

이 절차에서는 문자 배열로 저장된 데이터를 읽는 메서드를 DataTable 사용하는 GetChars 방법을 보여 줍니다. 다른 데이터 형식으로 인해 메서드가 GetChars .를 throw합니다 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

설명

GetChars 는 필드에서 사용 가능한 문자 수를 반환합니다. 대부분의 경우 필드의 정확한 길이입니다. 그러나 반환된 숫자는 필드에서 문자를 가져오는 데 이미 사용된 경우 GetChars 필드의 실제 길이보다 작을 수 있습니다.

필드의 끝에 도달하면 실제 읽은 문자 수가 요청된 길이보다 작을 수 있습니다. null(Visual Basic Nothing)인 버퍼를 전달하면 GetChars 버퍼 오프셋 매개 변수를 기반으로 하는 나머지 크기가 아니라 전체 필드의 길이를 문자 단위로 반환합니다.

변환은 수행되지 않습니다. 따라서 검색할 데이터는 이미 문자 배열이거나 문자 배열로 강제 변환할 수 있어야 합니다.

적용 대상