StreamReader.Read 方法

定義

自輸入資料流讀取下一個字元或下一組字元。

多載

Read()

自輸入資料流讀取下一個字元,並將字元位置前移一個字元。

Read(Span<Char>)

將目前資料流中的字元讀入至範圍。

Read(Char[], Int32, Int32)

從目前資料流讀取指定的字元數目上限,在指定的索引位置開始讀入緩衝區中。

Read()

Source:
StreamReader.cs
Source:
StreamReader.cs
Source:
StreamReader.cs

自輸入資料流讀取下一個字元,並將字元位置前移一個字元。

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

傳回

來自輸入資料流的下一個字元會以 Int32 物件來表示;如果不再有可以使用的字元,則以 -1 表示。

例外狀況

發生 I/O 錯誤。

範例

下列程式碼範例示範方法的 Read 簡單用法。

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 整數輸出格式化為十進位和十六進位。

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.Read

這個方法會傳回整數,以便在達到資料流程結尾時傳回 -1。 如果您在將資料讀取到緩衝區之後操作基礎資料流程的位置,基礎資料流程的位置可能不符合內部緩衝區的位置。 若要重設內部緩衝區,請呼叫 DiscardBufferedData 方法;不過,此方法會降低效能,而且只有在絕對必要時才應該呼叫。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

另請參閱

適用於

Read(Span<Char>)

Source:
StreamReader.cs
Source:
StreamReader.cs
Source:
StreamReader.cs

將目前資料流中的字元讀入至範圍。

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>

當這個方法傳回時,會包含讀取自目前來源之字元所取代的指定字元範圍。

傳回

已讀取字元數,或為 0 (如果處於資料流末端而無資料讀取)。 取決於是否可在資料流中使用資料,數目會小於或等於 buffer 的長度。

例外狀況

從資料流讀取的字元數大於 buffer 長度。

buffernull

適用於

Read(Char[], Int32, Int32)

Source:
StreamReader.cs
Source:
StreamReader.cs
Source:
StreamReader.cs

從目前資料流讀取指定的字元數目上限,在指定的索引位置開始讀入緩衝區中。

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) 的值之指定字元陣列,這個值是由從目前來源讀取的字元所取代。

index
Int32

要開始寫入的 buffer 的索引。

count
Int32

要讀取的字元數上限。

傳回

已讀取字元數,或為 0 (如果處於資料流末端而無資料讀取)。 數目將小於或等於 count 參數,取決於資料流內是否有資料可供使用。

例外狀況

緩衝區長度減去 index 會小於 count

buffernull

indexcount 為負。

發生 I/O 錯誤,例如資料流已關閉。

範例

下列程式碼範例會一次讀取五個字元,直到到達檔案結尾為止。

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.Read

這個方法會傳回整數,以便在到達資料流程結尾時傳回 0。

使用 Read 方法時,使用大小與資料流程內部緩衝區相同的緩衝區更有效率,其中內部緩衝區會設定為所需的區塊大小,而且一律讀取小於區塊大小。 如果在建構資料流程時未指定內部緩衝區的大小,則其預設大小為 4 KB (4096 個位元組) 。 如果您在將資料讀取到緩衝區之後操作基礎資料流程的位置,基礎資料流程的位置可能不符合內部緩衝區的位置。 若要重設內部緩衝區,請呼叫 DiscardBufferedData 方法;不過,此方法會降低效能,而且只有在絕對必要時才應該呼叫。

此方法會在讀取參數指定的 count 字元數或到達檔案結尾之後傳回。 ReadBlock 是 的 Read 封鎖版本。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

另請參閱

適用於