StreamReader.Read Metodo

Definizione

Legge il carattere successivo o il set di caratteri successivo dal flusso di input.

Overload

Read()

Legge il carattere successivo dal flusso di input e fa avanzare di un carattere la posizione del carattere.

Read(Span<Char>)

Legge i caratteri dal flusso corrente in un intervallo.

Read(Char[], Int32, Int32)

Legge un numero massimo specificato di caratteri dal flusso corrente e scrive i dati in un buffer, iniziando dall'indice specificato.

Read()

Legge il carattere successivo dal flusso di input e fa avanzare di un carattere la posizione del carattere.

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

Restituisce

Int32

Carattere successivo dal flusso di input rappresentato come oggetto Int32 oppure -1 se non sono disponibili altri caratteri.

Eccezioni

Si è verificato un errore di I/O.

Esempio

Nell'esempio di codice seguente viene illustrato un semplice utilizzo del Read metodo .

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

Nell'esempio di codice seguente viene illustrata la lettura di un singolo carattere usando l'overload del metodo , la formattazione dell'output integer ASCII come decimale ed Read() esadecimale.

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

Commenti

Questo metodo esegue l'override di TextReader.Read.

Questo metodo restituisce un numero intero in modo che possa restituire -1 se è stata raggiunta la fine del flusso. Se si modifica la posizione del flusso sottostante dopo la lettura dei dati nel buffer, la posizione del flusso sottostante potrebbe non corrispondere alla posizione del buffer interno. Per reimpostare il buffer interno, chiamare il metodo . Tuttavia, questo metodo rallenta le prestazioni e deve essere DiscardBufferedData chiamato solo quando assolutamente necessario.

Per un elenco delle attività di I/O comuni, vedere Attività di I/O comuni.

Vedi anche

Si applica a

Read(Span<Char>)

Legge i caratteri dal flusso corrente in un intervallo.

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

Parametri

buffer
Span<Char>

Al termine di questo metodo, contiene l'intervallo di caratteri specificato sostituiti con i caratteri letti dall'origine corrente.

Restituisce

Int32

Numero di caratteri letti oppure 0 se alla fine del flusso non è stato letto alcun dato. Il numero sarà minore o uguale alla lunghezza di buffer, a seconda che i dati siano disponibili o meno all'interno del flusso.

Eccezioni

Il numero di caratteri letti dal flusso è maggiore della lunghezza di buffer.

buffer è null.

Si applica a

Read(Char[], Int32, Int32)

Legge un numero massimo specificato di caratteri dal flusso corrente e scrive i dati in un buffer, iniziando dall'indice specificato.

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

Parametri

buffer
Char[]

Quando questo metodo viene restituito, il buffer contiene la matrice di caratteri specificata con i valori compresi tra index e (index + count - 1) sostituiti dai caratteri letti dall'origine corrente.

index
Int32

Indice di buffer da cui iniziare la scrittura.

count
Int32

Numero massimo di caratteri da leggere.

Restituisce

Int32

Numero di caratteri letti oppure 0 se alla fine del flusso non è stato letto alcun dato. Il numero sarà minore o uguale al parametro count, a seconda che i dati siano disponibili o meno all'interno del flusso.

Eccezioni

La lunghezza del buffer meno index è minore di count.

buffer è null.

index o count è negativo.

Si è verificato un errore di I/O, come la chiusura del flusso.

Esempio

Nell'esempio di codice seguente vengono letti cinque caratteri alla volta fino a quando non viene raggiunta la fine del file.

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

Commenti

Questo metodo esegue l'override di TextReader.Read.

Questo metodo restituisce un numero intero in modo che possa restituire 0 se è stata raggiunta la fine del flusso.

Quando si usa il metodo , è più efficiente usare un buffer delle stesse dimensioni del buffer interno del flusso, in cui il buffer interno è impostato sulle dimensioni del blocco desiderate e leggere sempre meno delle dimensioni del Read blocco. Se le dimensioni del buffer interno non sono specificate durante la costruzione del flusso, le dimensioni predefinite sono di 4 kilobyte (4096 byte). Se si modifica la posizione del flusso sottostante dopo la lettura dei dati nel buffer, la posizione del flusso sottostante potrebbe non corrispondere alla posizione del buffer interno. Per reimpostare il buffer interno, chiamare il metodo . Tuttavia, questo metodo rallenta le prestazioni e deve essere DiscardBufferedData chiamato solo quando assolutamente necessario.

Questo metodo restituisce dopo la lettura del numero di caratteri specificato dal parametro o dopo che è count stata raggiunta la fine del file. ReadBlock è una versione di blocco di Read .

Per un elenco delle attività di I/O comuni, vedere Attività di I/O comuni.

Vedi anche

Si applica a