StreamReader.Read StreamReader.Read StreamReader.Read StreamReader.Read Method

定義

自輸入資料流讀取下一個字元或下一組字元。Reads the next character or next set of characters from the input stream.

多載

Read() Read() Read() Read()

自輸入資料流讀取下一個字元,並將字元位置前移一個字元。Reads the next character from the input stream and advances the character position by one character.

Read(Span<Char>) Read(Span<Char>) Read(Span<Char>) Read(Span<Char>)
Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32)

從目前資料流讀取指定的字元數目上限,在指定的索引位置開始讀入緩衝區中。Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

Read() Read() Read() Read()

自輸入資料流讀取下一個字元,並將字元位置前移一個字元。Reads the next character from the input stream and advances the character position by one character.

public:
 override int Read();
public override int Read ();
override this.Read : unit -> int
Public Overrides Function Read () As Integer

傳回

來自輸入資料流的下一個字元會以 Int32 物件來表示;如果不再有可以使用的字元,則以 -1 表示。The next character from the input stream represented as an Int32 object, or -1 if no more characters are available.

例外狀況

發生 I/O 錯誤。An I/O error occurs.

範例

下列程式碼範例示範Read方法的簡單用法。The following code example demonstrates a simple use of the Read method.

using namespace System;
using namespace System::IO;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         while ( sr->Peek() >= 0 )
         {
            Console::Write( (Char)sr->Read() );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";

        try 
        {
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path)) 
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path)) 
            {
                while (sr.Peek() >= 0) 
                {
                    Console.Write((char)sr.Read());
                }
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                Console.Write(Convert.ToChar(sr.Read()))
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

下列程式碼範例將示範如何使用Read()方法多載來讀取單一字元,將 ASCII 整數輸出格式化為十進位和十六進位。The following code example demonstrates reading a single character using the Read() method overload, formatting the ASCII integer output as decimal and hexadecimal.

using namespace System;
using namespace System::IO;
int main()
{
   
   //Create a FileInfo instance representing an existing text file.
   FileInfo^ MyFile = gcnew FileInfo( "c:\\csc.txt" );
   
   //Instantiate a StreamReader to read from the text file.
   StreamReader^ sr = MyFile->OpenText();
   
   //Read a single character.
   int FirstChar = sr->Read();
   
   //Display the ASCII number of the character read in both decimal and hexadecimal format.
   Console::WriteLine( "The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar );
   
   //
   sr->Close();
}

using System;
using System.IO;

class StrmRdrRead
{
public static void Main()
    {
    //Create a FileInfo instance representing an existing text file.
    FileInfo MyFile=new FileInfo(@"c:\csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader sr=MyFile.OpenText();
    //Read a single character.
    int FirstChar=sr.Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        FirstChar, FirstChar);
    //
    sr.Close();
    }
}
Imports System.IO

Class StrmRdrRead
   
   Public Shared Sub Main()
      'Create a FileInfo instance representing an existing text file.
      Dim MyFile As New FileInfo("c:\csc.txt")
      'Instantiate a StreamReader to read from the text file.
      Dim sr As StreamReader = MyFile.OpenText()
      'Read a single character.
      Dim FirstChar As Integer = sr.Read()
      'Display the ASCII number of the character read in both decimal and hexadecimal format.
      Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar)
      sr.Close()
   End Sub
End Class

備註

這個方法覆寫 TextReader.ReadThis method overrides TextReader.Read.

這個方法會傳回整數,因此如果已到達資料流程末端,它可以傳回-1。This method returns an integer so that it can return -1 if the end of the stream has been reached. 如果您在將資料讀入緩衝區之後操作基礎資料流程的位置,基礎資料流程的位置可能不符合內部緩衝區的位置。If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. 若要重設內部緩衝區, 請DiscardBufferedData呼叫方法; 不過, 這個方法會降低效能, 而且只有在絕對必要時才應呼叫。To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.

如需一般 i/o 工作的清單, 請參閱一般 i/o工作。For a list of common I/O tasks, see Common I/O Tasks.

另請參閱

Read(Span<Char>) Read(Span<Char>) Read(Span<Char>) Read(Span<Char>)

public:
 override int Read(Span<char> buffer);
public override int Read (Span<char> buffer);
override this.Read : Span<char> -> int
Public Overrides Function Read (buffer As Span(Of Char)) As Integer

參數

buffer
Span<Char>

傳回

Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32)

從目前資料流讀取指定的字元數目上限,在指定的索引位置開始讀入緩衝區中。Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.

public:
 override int Read(cli::array <char> ^ buffer, int index, int count);
public override int Read (char[] buffer, int index, int count);
override this.Read : char[] * int * int -> int
Public Overrides Function Read (buffer As Char(), index As Integer, count As Integer) As Integer

參數

buffer
Char[]

當這個方法傳回時,會包含指定的字元陣列,這個陣列具有介於 index 到 (index + count - 1) 之間的值,已由讀取自目前來源的字元所取代。When this method returns, contains the specified character array with the values between index and (index + count - 1) replaced by the characters read from the current source.

index
Int32 Int32 Int32 Int32

要開始寫入的 buffer 的索引。The index of buffer at which to begin writing.

count
Int32 Int32 Int32 Int32

要讀取的字元數上限。The maximum number of characters to read.

傳回

已讀取字元數,或為 0 (如果處於資料流末端而無資料讀取)。The number of characters that have been read, or 0 if at the end of the stream and no data was read. 數目將小於或等於 count 參數,取決於資料流裡是否有資料可供使用。The number will be less than or equal to the count parameter, depending on whether the data is available within the stream.

例外狀況

緩衝區長度減去 index 會小於 countThe buffer length minus index is less than count.

發生 I/O 錯誤,例如資料流已經關閉。An I/O error occurs, such as the stream is closed.

範例

下列程式碼範例會一次讀取五個字元,直到到達檔案結尾為止。The following code example reads five characters at a time until the end of the file is reached.

using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   try
   {
      if ( File::Exists( path ) )
      {
         File::Delete( path );
      }
      StreamWriter^ sw = gcnew StreamWriter( path );
      try
      {
         sw->WriteLine( "This" );
         sw->WriteLine( "is some text" );
         sw->WriteLine( "to test" );
         sw->WriteLine( "Reading" );
      }
      finally
      {
         delete sw;
      }

      StreamReader^ sr = gcnew StreamReader( path );
      try
      {
         //This is an arbitrary size for this example.
         array<Char>^c = nullptr;
         while ( sr->Peek() >= 0 )
         {
            c = gcnew array<Char>(5);
            sr->Read( c, 0, c->Length );
            
            //The output will look odd, because
            //only five characters are read at a time.
            Console::WriteLine( c );
         }
      }
      finally
      {
         delete sr;
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }
}
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";

        try 
        {
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path)) 
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path)) 
            {
                //This is an arbitrary size for this example.
                char[] c = null;

                while (sr.Peek() >= 0) 
                {
                    c = new char[5];
                    sr.Read(c, 0, c.Length);
                    //The output will look odd, because
                    //only five characters are read at a time.
                    Console.WriteLine(c);
                }
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                'This is an arbitrary size for this example.
                Dim c(5) As Char
                sr.Read(c, 0, c.Length)
                'The output will look odd, because
                'only five characters are read at a time.
                Console.WriteLine(c)
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

備註

這個方法覆寫 TextReader.ReadThis method overrides TextReader.Read.

這個方法會傳回整數,因此如果已經到達資料流程末端,它就會傳回0。This method returns an integer so that it can return 0 if the end of the stream has been reached.

使用Read方法時,使用與資料流程內部緩衝區相同大小的緩衝區會更有效率,其中內部緩衝區設定為您想要的區塊大小,而且一律讀取小於區塊大小。When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. 如果在建立資料流程時未指定內部緩衝區的大小,其預設大小為 4 kb (4096個位元組)。If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). 如果您在將資料讀入緩衝區之後操作基礎資料流程的位置,基礎資料流程的位置可能不符合內部緩衝區的位置。If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. 若要重設內部緩衝區, 請DiscardBufferedData呼叫方法; 不過, 這個方法會降低效能, 而且只有在絕對必要時才應呼叫。To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.

這個方法會在讀取count參數所指定的字元數之後傳回,或到達檔案結尾。This method returns after either the number of characters specified by the count parameter are read, or the end of the file is reached. ReadBlock是的封鎖版本ReadReadBlock is a blocking version of Read.

如需一般 i/o 工作的清單, 請參閱一般 i/o工作。For a list of common I/O tasks, see Common I/O Tasks.

另請參閱

適用於