StreamReader.Read 方法

定義

讀取輸入串流中的下一個字元或下一組字元。

多載

名稱 Description
Read()

從輸入串流讀取下一個字元,並將字元位置前進一個字元。

Read(Span<Char>)

將當前串流中的字元讀入一個區間。

Read(Char[], Int32, Int32)

從指定索引開始,從目前串流讀取指定最大字元數到緩衝區。

Read()

來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
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 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 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 任務的清單,請參見 Common I/O 任務

另請參閱

適用於

Read(Span<Char>)

來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
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)

來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
StreamReader.cs
來源:
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 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.ReadBlock(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.ReadBlock(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 任務的清單,請參見 Common I/O 任務

另請參閱

適用於